Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

dplyr

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)
like image 536
lucazav Avatar asked Oct 28 '25 11:10

lucazav


1 Answers

We can use rowSums after subsetting the columns of the dataset

library(dplyr)
df %>% 
      mutate(TotalEvaluation = rowSums(.[myvars]))
like image 106
akrun Avatar answered Oct 30 '25 02:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!