Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turn a data frame column into vector with names as row names

I have an output which looks like the following code:

data.frame(H = c(1.5,4.5,5,8)) %>% `rownames<-`(c("a","b","c","d"))
    H
a 1.5
b 4.5
c 5.0
d 8.0

Ideally, using dplyr, I would like to convert it to a vector like this:

  a   b   c   d 
1.5 4.5 5.0 8.0 

Is there anyway I can do this without defining any new variables and using only the pipe operator?
Using unlist will not result in the desired outcome.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

data.frame(H = c(1.5,4.5,5,8)) %>% `rownames<-`(c("a","b","c","d")) %>% unlist()

    H1  H2  H3  H4 
    1.5 4.5 5.0 8.0

>Solution :

With rownames_to_column + deframe from tibble:

library(tibble)
df %>% 
  rownames_to_column() %>% 
  deframe()

#  a   b   c   d 
#1.5 4.5 5.0 8.0 

Another option with pull

library(dplyr)
library(tibble)
df %>% 
  rownames_to_column() %>% 
  pull(H, rowname)

Or with the exposition pipe %$%:

library(magrittr)
df %$% 
  set_names(H, rownames(.))

For the sake of completeness, the base R one-liner:

setNames(df$H, rownames(df))

That can also be piped, with magrittr‘s %$%:

df %$% 
  setNames(H, rownames(.))

Data:

df <- data.frame(H = c(1.5,4.5,5,8)) %>% 
  `rownames<-`(c("a","b","c","d"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading