Comparing variables of with a vector of solutions

  • A+

I am facing the following problem. I have a test with multiple questions and the answers of the subjects are recorded in the variables Q1 to Q3 (in reality I have many more questions)

test <- tibble(   Q1 = c(4, 5, 6),    Q2 = c(3, 2, 1),     Q3 = c(4, 1, 3)) 

I put the correct answers for questions 1, 2 and 3 in a vector

correct_answers <- c(4,2,3) 

And now I to create a new variable that counts the number of correct answers for each subject. My guess is that it works with a map2 function and, but I could not figure out how.


We can create a logical matrix in base R and then do the rowSums to count the number of correct answers

test$newCol <- rowSums(test == correct_answers[col(test)]) 

Or using tidyverse, using map2 with reduce to create a 'newCol' in the dataset

library(tidyverse) test %>%        mutate(newCol = map2(., correct_answers, `==`) %>%                         reduce(`+`)) 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: