Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass column name as parameter to function in dplyr?

I want to do the same as here but with dplyr and one more column.

I want to selecting a column via a string variable, but on top I also want to select a second column normally. I need this because I have a function which selects a couple of columns by a given parameters.

I have the following code as an example:

library(dplyr)
data(cars)

x <- "speed"
cars %>% select_(x, dist)
like image 601
lony Avatar asked Jan 29 '15 19:01

lony


2 Answers

You can use quote() for the dist column

x <- "speed"
cars %>% select_(x, quote(dist)) %>% head
#   speed dist
# 1     4    2
# 2     4   10
# 3     7    4
# 4     7   22
# 5     8   16
# 6     9   10
like image 140
Rich Scriven Avatar answered Oct 09 '22 08:10

Rich Scriven


I know I'm a little late to this one, but I figured I would add it for others.

x <- "speed"
cars %>% select(one_of(x),dist) %>% head()
##   speed dist
## 1     4    2
## 2     4   10
## 3     7    4
## 4     7   22
## 5     8   16
## 6     9   10

OR this would work too

cars %>% select(one_of(c(x,'dist')))
like image 39
Brian P. Avatar answered Oct 09 '22 06:10

Brian P.