Search code examples
rdplyrsubsetr-rownames

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.

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