Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing variables of with a vector of solutions

Tags:

r

purrr

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.

like image 808
econgr Avatar asked Jan 21 '19 11:01

econgr


3 Answers

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(`+`))
like image 190
akrun Avatar answered Oct 02 '22 19:10

akrun


Does this work?

library(purrr)
test %>% 
  map_dbl(~sum(.x%in%correct_answers))
like image 33
NelsonGon Avatar answered Oct 02 '22 18:10

NelsonGon


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))
like image 45
Ronak Shah Avatar answered Oct 02 '22 17:10

Ronak Shah