dplyr ::选择一列并输出为向量

时间:2014-11-26 12:30:34

标签: r select vector dataframe dplyr

dplyr::select会生成一个data.frame,如果结果是一列,有没有办法让它返回一个向量?

目前,我必须执行额外步骤(res <- res$y)将其转换为data.frame中的vector,请参阅此示例:

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

如下所示:

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"

3 个答案:

答案 0 :(得分:99)

最佳方式(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)

答案 1 :(得分:7)

这样的东西?

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

答案 2 :(得分:3)

您也可以尝试

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

 class(res)
#[1] "character"