dplyr::select one column and output as vector

39,280

Solution 1

The best way to do it (IMO):

library(dplyr)
df <- data_frame(x = 1:10, y = LETTERS[1:10])

df %>% 
  filter(x > 5) %>% 
  .$y

In dplyr 0.7.0, you can now use pull():

df %>% filter(x > 5) %>% pull(y)

Solution 2

Something like this?

> res <- df %>% filter(x>5) %>% select(y) %>% sapply(as.character) %>% as.vector
> res
[1] "F" "G" "H" "I" "J"
> class(res)
[1] "character"

Solution 3

You could also try

res <- df %>%
           filter(x>5) %>%
           select(y) %>%
           as.matrix() %>%
           c()
#[1] "F" "G" "H" "I" "J"

 class(res)
#[1] "character"
Share:
39,280

Related videos on Youtube

zx8754
Author by

zx8754

Analysis - Data - Analysis - Data - Volleyball r

Updated on October 27, 2020

Comments

  • zx8754
    zx8754 over 3 years

    dplyr::select results in a data.frame, is there a way to make it return a vector if the result is one column?

    Currently, I have to do extra step (res <- res$y) to convert it to vector from data.frame, see this example:

    #dummy data
    df <- data.frame(x = 1:10, y = LETTERS[1:10], stringsAsFactors = FALSE)
    
    #dplyr filter and select results in data.frame
    res <- df %>% filter(x > 5) %>% select(y)
    class(res)
    #[1] "data.frame"
    
    #desired result is a character vector
    res <- res$y
    class(res)
    #[1] "character"
    

    Something as below:

    res <- df %>% filter(x > 5) %>% select(y) %>% as.character
    res
    # This gives strange output
    [1] "c(\"F\", \"G\", \"H\", \"I\", \"J\")"
    
    # I need:
    # [1] "F" "G" "H" "I" "J"
    
    • zx8754
      zx8754 over 9 years
      @Henrik Yes, you are right. I saw that post, somehow couldn't replicate, hence this post. Now it works! df %>% filter(x>5) %>% select(y) %>% .[["y"]].
    • nacnudus
      nacnudus over 8 years
      This is not a duplicate. The other question is specific to table with database back-ends, where the answer to this question (%>% .$y) does not work.
  • Andy
    Andy almost 9 years
    Could you point to the documentation on the dot operator in this context?
  • hadley
    hadley almost 9 years
    @Andy see the magrittr docs
  • ianmcook
    ianmcook almost 7 years
    In dplyr 0.7.0, you can now use pull(): df %>% filter(x > 5) %>% pull(y)
  • lefft
    lefft over 6 years
    surprised not to see the %$% pipe from magrittr::! As in: df %>% filter(x>5) %$% y