mardi 29 décembre 2020

How can I combine the "paste" command with the "ifelse" command in a for loop with R?

For Loop in R including paste and ifelse

Dear Community,

I'm trying to combine a paste command in combination with an ifelse command in a for loop with R Studio - but I'm receiving the error message Error: Unexpected '}' in "}".

Download simplified Dataset:

I have created a simple dataset to illustrate my problem. You can download via the following link: https://www.dropbox.com/scl/fi/jxvcfvxnv7pf8e74tulzq/Data.xlsx?dl=0&rlkey=de7b3e2d0ge8ju6tsvz2bkzuv

Background:

I would like evaluate empirical data from a test. Therefore I need to create a new column (called Point.[i]) for every item (i = 1-4). If the value in the "Answer.[i]"-column corresponds to the value of the "Right.Answer.[i]"-column, I would like to give 1 point (otherwise 0 points) for that task.

My Code

This is easy for one column:

data1 <- mutate(data, Point.1 = ifelse(Answer.1 == Right.Answer.1, 1, 0)) 

Now I would like write a for loop doing this for all columns, but the following code is not working:


for (i in 1:4) {
  data[i] <- mutate(data, paste("Answer.",i) = ifelse(paste("Answer.",i) == paste("Answer.",i), 1, 0))
  print(data)
}

I would be very grateful for any advice. Thanks in advance!

Karla

Aucun commentaire:

Enregistrer un commentaire