简体   繁体   中英

Replace values from multiple columns using a vector with key values in R

I´m working with an exam, and my intention is to automatize the process of replacing the response given for a 1 if it is correct and a 0 if it is incorrect, based on a vector with the right answer for each question.

Suppose I have a matrix that looks like this

math_exam=data.frame(item1=c("a","b","a","c","d"), item2=c("b","b","c","c","a"), item3=c("b","c","a","c","d"))


  item1 item2 item3
1     a     b     b
2     b     b     c
3     a     c     a
4     c     c     c
5     d     a     d

And a vector with the correct answer that looks like this key <- c("a","c","b")

My intention is to create a simple loop or a function that allows me to use these two objects to generate a matrix like this one:

  item1 item2 item3
1     1     0     1
2     0     0     0
3     1     1     0
4     0     1     0
5     0     0     0

I want to be able to automatize this so regardless of the number of items on the matrix, as long as the vector matches that number, the function or loop will work.

I´d really appreciate any advise or tip on how to achieve this. Thank you.

We can replicate the 'key' and use == to create a logical matrix, that can be coerced to binary with +

math_exam[] <- +(math_exam == key[col(math_exam)])

-output

math_exam
#  item1 item2 item3
#1     1     0     1
#2     0     0     0
#3     1     1     0
#4     0     1     0
#5     0     0     0

Or use sweep

+(sweep(math_exam, 2, key, `==`))

Or using mapply

+(mapply(`==`, math_exam, key))

Using transpose -

math_exam[] <- +t(t(math_exam) == key)
math_exam

#  item1 item2 item3
#1     1     0     1
#2     0     0     0
#3     1     1     0
#4     0     1     0
#5     0     0     0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM