mrestko mrestko - 3 years ago 113
R Question

Select list of columns from a data frame using dplyr and select_()

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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download