Search code examples
rvariablesdplyr

How can I have use variables in the calculations of mutate function?


Consider this famous table (already exists in R)

 head(iris)


Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

Please notice that it has a column named Sepal.Length. I defined a variable with the same name. Please consider this code:

table = iris
Sepal.Length = 0
table2 = table %>% mutate ( new = Sepal.Length*Petal.Length )

If you check the result:

head(table2)


Sepal.Length Sepal.Width Petal.Length Petal.Width Species  new
1          5.1         3.5          1.4         0.2  setosa 0.28
2          4.9         3.0          1.4         0.2  setosa 0.28
3          4.7         3.2          1.3         0.2  setosa 0.26
4          4.6         3.1          1.5         0.2  setosa 0.30
5          5.0         3.6          1.4         0.2  setosa 0.28
6          5.4         3.9          1.7         0.4  setosa 0.68

As you see, the variable Sepal.Length = 0 has been ignored and the column table$Sepal.Length has been taken into account for creating the new column.

How can I have use variables in the calculations of mutate function?


Solution

  • Alternatively, put !! in front of Sepal.Length as noted here https://stackoverflow.com/a/47659705/13015865

    packages

    library(dplyr)
    

    Solution

    table <- iris #no need to change the name of the dataset. But ok. 
    Sepal.Length <- 0
    
    table %>% mutate ( new = !!Sepal.Length*Petal.Length ) 
    

    output (head)

      Sepal.Length Sepal.Width Petal.Length Petal.Width Species new
    1          5.1         3.5          1.4         0.2  setosa   0
    2          4.9         3.0          1.4         0.2  setosa   0
    3          4.7         3.2          1.3         0.2  setosa   0
    4          4.6         3.1          1.5         0.2  setosa   0
    5          5.0         3.6          1.4         0.2  setosa   0
    6          5.4         3.9          1.7         0.4  setosa   0