1

I want to set a column as an index in R.

x<-data.frame(x=c(1,4,5,6,7),y=c(5,7,8,5,9))
x
  x y
1 1 5
2 4 7
3 5 8
4 6 5
5 7 9

I want to set x as an index and get the following output:

  y
1 5
4 7
5 8
6 5
7 9
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
user86907
  • 817
  • 9
  • 21

1 Answers1

2

We can use column_to_rownames from tibble

library(tibble)
x1 <- x %>%
         column_to_rownames('x')

Or with deframe

deframe(x) %>% 
        data.frame(y = .)

Or with base R

`row.names<-`(x[-1], x$x)
#  y
#1 5
#4 7
#5 8
#6 5
#7 9
akrun
  • 874,273
  • 37
  • 540
  • 662
  • but how can i make the values numeric once setting x as an index. Can you please help me with this as well. Thanks @akrun – user86907 Sep 10 '20 at 06:07
  • @user86907 the `row.names` attribute would be a character class. You can use `as.integer(row.names(x1))` to convert to numeric. The reverse option in tidyverse is `rownames_to_column(x1, 'rn') %>% type.convert(as.is = TRUE)` – akrun Sep 10 '20 at 06:08