Specifying row names when reading in a file

2019-02-04 00:53发布

I have a .txt file that contains row names. However, R set the row names as the first column.

2条回答
手持菜刀,她持情操
2楼-- · 2019-02-04 01:23

See ?read.table. Basically, when you use read.table, you specify a number indicating the column:

##Row names in the first column
read.table(filname.txt, row.names=1)
查看更多
Melony?
3楼-- · 2019-02-04 01:36

If you used read.table() (or one of it's ilk, e.g. read.csv()) then the easy fix is to change the call to:

read.table(file = "foo.txt", row.names = 1, ....)

where .... is other arguments you needed/used. The row.names argument take the column number of the data file from which to take the row names. It need not be the first column. See ?read.table for details/info.

If you already have the data in R and can;t be bothered to re-read it, or is came from another route, just set the rownames attribute and remove the first variable from the object (assuming obj is your object)

rownames(obj) <- obj[, 1] ## set rownames
obj <- obj[, -1]          ## remove the first variable
查看更多
登录 后发表回答