Using variables for column functions in mutate()

前端 未结 2 485
囚心锁ツ
囚心锁ツ 2021-01-19 17:54

How can I use variables in place of column names in dplyr strings? As an example say I want to add a column to the iris dataset called sum that is the sum o

相关标签:
2条回答
  • 2021-01-19 18:20

    I think that recommended way is using sym:

    iris %>% mutate(sum = !!sym(x) + !!sym(y)) %>% head
    
    0 讨论(0)
  • 2021-01-19 18:26

    It also works with get():

    > rm(list = ls())
    > data("iris")
    > 
    > library(dplyr)
    > 
    > x <- "Sepal.Length"
    > y <- "Sepal.Width"
    > 
    > head(iris %>% mutate(sum = get(x) + get(y)))
      Sepal.Length Sepal.Width Petal.Length Petal.Width Species sum
    1          5.1         3.5          1.4         0.2  setosa 8.6
    2          4.9         3.0          1.4         0.2  setosa 7.9
    3          4.7         3.2          1.3         0.2  setosa 7.9
    4          4.6         3.1          1.5         0.2  setosa 7.7
    5          5.0         3.6          1.4         0.2  setosa 8.6
    6          5.4         3.9          1.7         0.4  setosa 9.3
    
    0 讨论(0)
提交回复
热议问题