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"
答案 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"