I have a dataframe that looks like this, and would like to convert the left-most column into an actual index, with the label "id".
I tried to rename it with colnames<- but it didn't work, as ncol() only returns 2. I tried to export it as a csv file, but index was similarly not captured in the file.
CodePudding user response:
There are a couple ways to do this. Firstly, the method you used to write to csv you can also include the row.names = TRUE parameter in the write.csv function. Otherwise, the following commands also work:
library(tibble)
df <- tibble::rownames_to_column(df, "VALUE")
(taken from Convert row names into first column)
CodePudding user response:
Example data
d <- data.frame(layer=2:4, gridpop=c(1000,2000,3000))
rownames(d) <- c("A", "B", "C")
d
# layer gridpop
#A 2 1000
#B 3 2000
#C 4 3000
Solution
d$id <- rownames(d)
d
# layer gridpop id
#A 2 1000 A
#B 3 2000 B
#C 4 3000 C
Or if the row names represent numbers
d$id <- as.numeric(rownames(d))

