0

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".

Dataframe

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.

camille
  • 16,432
  • 18
  • 38
  • 60
  • 1
    Welcome to SO! Please don't upload code or data as images for [these reasons](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557). – Limey Jan 20 '22 at 16:10
  • 1
    Does this answer your question? [Convert row names into first column](https://stackoverflow.com/questions/29511215/convert-row-names-into-first-column) – Limey Jan 20 '22 at 16:12

2 Answers2

0

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)

dthorbur
  • 155
  • 1
  • 11
0

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))
Robert Hijmans
  • 40,301
  • 4
  • 55
  • 63