且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用dplyr和select_()从数据框中选择列列表,

更新时间:2023-02-05 18:16:32

您只是错过了 .dots code code code code code code code code code code code code code code $ c $ (数据){
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