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(`+`))
Does this work?
library(purrr)
test %>%
map_dbl(~sum(.x%in%correct_answers))
We could use mapply
and then do rowSums
df$ans <- rowSums(mapply(`==`, test, correct_answers))
With map2
it could be something like
library(purrr)
map2(test, correct_answers, function(x, y) sum(x == y))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With