65

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

2 Answers 2

99

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
Sign up to request clarification or add additional context in comments.

3 Comments

You could also use column-based slicing (at least for matrix and dataframe). rownames(obj) <- t(obj[1]) ##get row names from first column obj <- obj[-1] ## remove first column
So, the integer for row.names is 1-indexed? The first column isn't called Column 0?
@Dr_Hope All vectors at the R level are 1-indexed, hence the first row is row 1 and the first column is column 1.
8

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.