dplyr::选择一列并输出为向量 [英] dplyr::select one column and output as vector

查看:26
本文介绍了dplyr::选择一列并输出为向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

dplyr::select results in a data.frame, is there a way to make it return a vector if the result is one column?

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

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"

如下:

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"

推荐答案

最好的方法 (IMO):

The best way to do it (IMO):

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

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

<小时>

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


In dplyr 0.7.0, you can now use pull():

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

这篇关于dplyr::选择一列并输出为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆