When I remove the first column, row.names are removed too?

1.1k Views Asked by At
df <- data.frame(col1=c('row1','row2','row3'),col2=c(1,1,1),col3=c(0,0.5,2))
> row.names(df) <- df$col1
> df
     col1 col2 col3
row1 row1    1  0.0
row2 row2    1  0.5
row3 row3    1  2.0
> df <- select(df, -starts_with("col1"))
> df
     col2 col3
row1    1  0.0
row2    1  0.5
row3    1  2.0

What I did above is not functioning with my real code. So I have a data.frame in R. I make the first column the row.names. Now I want to remove the first column but when I do this, the row.names are removed too (an get converted into numbering). Unfortunately I can´t reproduce my mistake. With df it works well how it should. With my data it looks like this

     col2 col3
   1   1  0.0
   2   1  0.5
   3   1  2.0

What is a reason (and solution) for that?

Thank you

1

There are 1 best solutions below

0
On

You can simply deselect col1:

df <- data.frame(col1=c('row1','row2','row3'),col2=c(1,1,1),col3=c(0,0.5,2))
row.names(df) <- df$col1

Subset df by deselecting col1:

df[,-1]
     col2 col3
row1    1  0.0
row2    1  0.5
row3    1  2.0