dplyr::select one column and output as vector

RSelectVectorDataframeDplyr

R Problem Overview


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"

R Solutions


Solution 1 - R

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 - R

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 - R

You could also try

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

 class(res)
#[1] "character"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionzx8754View Question on Stackoverflow
Solution 1 - RhadleyView Answer on Stackoverflow
Solution 2 - RLyzandeRView Answer on Stackoverflow
Solution 3 - RakrunView Answer on Stackoverflow