error in adding the first column as the row name in r -
i'm trying name row names first column in r. error invalid 'row.names' length
present.
df
x1 b 1 2 1 2 b 4 2
expected output
b 2 1 b 4 2
my code
df1 <- df[, -1] #remove first column x1 , create new df->df1 rownames(df1) <- df[, 1] #add row names first column of df
error
error in `row.names<-.data.frame`(`*tmp*`, value = value) : invalid 'row.names' length
thanks!
to complete first answer, 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, understand why initial data.frame gave error in setting row.names, because of subsetting. you'll see not vector:
dim(df[, 1]) #### [1] 2 1
it's due particularities of tibble format of initial data.frame. @thelatemail help.
Comments
Post a Comment