使用dplyr和select_()从数据框中选择列列表, [英] Select list of columns from a data frame using dplyr and select_()

查看:706
本文介绍了使用dplyr和select_()从数据框中选择列列表,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下函数从数据框架中提取一些列:

  library('dplyr' )
desired_columns = c(
'a',
'b',
'c')
extract_columns< - function(data){
extracted_data< - data%>%
select_(desired_columns)
return(extracted_data)
}

但是,当我尝试它,我没有得到我的期望:

 > df<  -  data.frame(a = 1:5,b = 1:5,c = 1:5,d = 1:5)
> df
abcd
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
> extract_columns(df)
a
1 1
2 2
3 3
4 4
5 5
/ pre>

我似乎只得到第一列,我无法弄清楚我做错了什么。如何获取所有请求的列?

解决方案

您只是错过了 .dots extracted_data< - data%>%
select _(。dots = desired_columns)
return(extracted_data)
}

extract_columns (df)
abc
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5


I'm trying to use the following function to extract some columns from a data frame:

library('dplyr')
desired_columns = c(
  'a',
  'b',
  'c')
extract_columns <- function(data) {
  extracted_data <- data %>%
    select_(desired_columns)
  return(extracted_data)
}

But when I try it, I don't get what I expect:

> df <- data.frame(a=1:5, b=1:5, c=1:5, d=1:5)
> df
  a b c d
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
> extract_columns(df)
  a
1 1
2 2
3 3
4 4
5 5

I seem to be only getting the first column and I can't figure out what I'm doing wrong. How can I get all the requested columns?

解决方案

You are just missing the .dots argument in select_:

extract_columns <- function(data) {
    extracted_data <- data %>%
        select_(.dots = desired_columns)
    return(extracted_data)
}

extract_columns(df)
  a b c
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5

这篇关于使用dplyr和select_()从数据框中选择列列表,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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