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

zx8*_*754 61 select r vector dataframe dplyr

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

目前,我必须执行额外的step(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"
Run Code Online (Sandbox Code Playgroud)

如下:

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"
Run Code Online (Sandbox Code Playgroud)

had*_*ley 108

最好的方法(IMO):

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

df %>% 
  filter(x > 5) %>% 
  .$y
Run Code Online (Sandbox Code Playgroud)

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

df %>% filter(x > 5) %>% pull(y)
Run Code Online (Sandbox Code Playgroud)

  • 在dplyr 0.7.0中,你现在可以使用`pull()`:`df%>%filter(x> 5)%>%pull(y)` (13认同)
  • 您是否可以在此上下文中指向点运算符的文档? (5认同)
  • @Andy查看magrittr文档 (2认同)
  • 惊讶没有看到`magrittr ::`的`%$%`管道!如:`df%>%filter(x> 5)%$%y` (2认同)

Lyz*_*deR 8

像这样的东西?

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


akr*_*run 5

你也可以试试

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

 class(res)
#[1] "character"
Run Code Online (Sandbox Code Playgroud)