Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying row names when reading in a file

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

like image 657
fokos Avatar asked Nov 07 '12 14:11

fokos


People also ask

What is the function to set Row names?

`. rowNamesDF<-` is a (non-generic replacement) function to set row names for data frames, with extra argument make. names .

Do Tibbles create row names?

While a tibble can have row names (e.g., when converting from a regular data frame), they are removed when subsetting with the [ operator. A warning will be raised when attempting to assign non- NULL row names to a tibble.

What does row names 1 do in R?

Assigning the second argument, row. names , to be 1 indicates that the data file has row names, and which column number they are stored in. If we don't specify row. names the result will not have row names.


2 Answers

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 .... are the other arguments you needed/used. The row.names argument takes 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 it 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 
like image 57
Gavin Simpson Avatar answered Oct 11 '22 16:10

Gavin Simpson


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) 
like image 44
csgillespie Avatar answered Oct 11 '22 17:10

csgillespie