lucazav
lucazav

Reputation: 878

dplyr: Evaluate the sum of variables whose names are in a vector

I need to programmatically add multiple variables whose name is in a vector. For example, given this vector:

myvars <- c("Expectation", "Interesting", "Useful", "OralPresentation")

how can I write the following expression using the previous vector?

df %>%
  mutate(TotalEvaluation = Expectation + Interesting + Useful + OralPresentation)

Upvotes: 4

Views: 416

Answers (2)

Daniel
Daniel

Reputation: 7832

You could use sjmisc::row_sums(), which appends the rowsums to the end of the data frame by default:

library(sjmisc)
data("iris")
col <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
row_sums(iris, col, n = 1)
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species rowsums
#> 1            5.1         3.5          1.4         0.2     setosa    10.2
#> 2            4.9         3.0          1.4         0.2     setosa     9.5
#> 3            4.7         3.2          1.3         0.2     setosa     9.4
#> 4            4.6         3.1          1.5         0.2     setosa     9.4
#> 5            5.0         3.6          1.4         0.2     setosa    10.2
#> 6            5.4         3.9          1.7         0.4     setosa    11.4
#> ...

or just the new variable:

row_sums(iris, col, n = 1, append = FALSE)
#>     rowsums
#> 1      10.2
#> 2       9.5
#> 3       9.4
#> 4       9.4
#> 5      10.2
#> 6      11.4
#> ...

or with new variable name...

row_sums(iris, col, n = 1, var = "TotalEvaluation")
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species TotalEvaluation
#> 1            5.1         3.5          1.4         0.2     setosa            10.2
#> 2            4.9         3.0          1.4         0.2     setosa             9.5
#> 3            4.7         3.2          1.3         0.2     setosa             9.4
#> 4            4.6         3.1          1.5         0.2     setosa             9.4
#> 5            5.0         3.6          1.4         0.2     setosa            10.2
#> 6            5.4         3.9          1.7         0.4     setosa            11.4
#> ...

row_sums() works seamlessly together with dplyr and/or pipe-operator.

Upvotes: 0

akrun
akrun

Reputation: 887391

We can use rowSums after subsetting the columns of the dataset

library(dplyr)
df %>% 
      mutate(TotalEvaluation = rowSums(.[myvars]))

Upvotes: 3

Related Questions