【发布时间】:2015-01-24 18:57:48
【问题描述】:
dplyr::select 产生一个data.frame,如果结果是一列,有没有办法让它返回一个向量?
目前,我必须做额外的步骤 (res <- res$y) 才能将其从 data.frame 转换为矢量,请参阅此示例:
#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"
【问题讨论】:
-
@Henrik 是的,你是对的。我看到那个帖子,不知何故无法复制,因此这个帖子。现在它起作用了!
df %>% filter(x>5) %>% select(y) %>% .[["y"]]. -
这不是重复的。另一个问题特定于具有数据库后端的表,该问题的答案 (
%>% .$y) 不起作用。
标签: r select vector dataframe dplyr