Imagine for a collected questionnaire for dozens of subjects, I want to check whether the answers are correct for each question. To achieve this column-wise manipulation, I use the mapply function, where the vectorized pairs are columns(multiple variables) and vectors (multiple elements) respectively, see below the demo code for details. However, with such a method, I need to generate the variables manually to incorporate it into the original data frame, therefore, I wonder if there is an alternative method with which it can achieve a similar effect using the multivariate version of mutate function in dplyr packages? so it will not necessary to generate the names of the variables manually and realized it in a vectorized manner.
##simulated data generation with four questions
IDs<-paste0('subj',0,1:7)
Q1<-c('A','B','C','A','A','A','D')
Q2<-c('A','B','B','B','B','D','C')
Q3<-c('B','B','C','C','C','D','C')
Q4<-c('A','D','D','B','D','D','C')
vect<-data.frame(cbind(IDs,Q1,Q2,Q3,Q4))
##answer for the four questions
answer<-c('A','B','C','D')
##method with mapply function
myfunc<-function(vec,value) {
ifelse(vec==value, TRUE, FALSE)
}
newvariable<-mapply(myfunc, vect[,2:5], answer)
colnames(newvariable)<-paste0('Q',1:4,"_ans")
newvariable
vect_new1<-cbind(vect,newvariable)
vect_new1