dplyr::select one column and output as vector

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"
41597 次浏览

像这样吗?

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

你也可以试试

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


class(res)
#[1] "character"

做到这一点的最佳方法(IMO) :

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


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

在 dplyr 0.7.0中,现在可以使用 pull () :

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