I have a .txt
file that contains row names. However, R set the row names as the first column.
`. rowNamesDF<-` is a (non-generic replacement) function to set row names for data frames, with extra argument make. 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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With