Reputation: 1383
I'm trying to name my row names by the first column in R. But error invalid 'row.names' length
present.
df
x1 A B
1 a 2 1
2 b 4 2
expected output
A B
a 2 1
b 4 2
my code
df1 <- df[, -1] #remove the first column x1 and create a new df->df1
rownames(df1) <- df[, 1] #add the row names by the first column of df
Error
Error in `row.names<-.data.frame`(`*tmp*`, value = value) : invalid 'row.names' length
Thanks!
Upvotes: 4
Views: 6690
Reputation: 8377
To complete the first answer, I can suggest also:
library(magrittr)
df %>% data.frame %>% set_rownames(.$x1) %>% select(-x1)
or
library(tibble)
data.frame(column_to_rownames(df, var = "x1"))
Eventually, to understand why your initial data.frame gave an error in setting the row.names, its because of the subsetting. You'll see this is not really a vector:
dim(df[, 1])
#### [1] 2 1
It's due to particularities of the tibble format of your initial data.frame. Thanks to @thelatemail for the help.
Upvotes: 2