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

▼魔方 西西 提交于 2019-12-09 15:16:04

问题


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)

回答1:


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



回答2:


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')))


来源:https://stackoverflow.com/questions/28222876/how-to-pass-column-name-as-parameter-to-function-in-dplyr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!