0
votes

I'm new here and beginner at R.

I'm currently struggling with the following problem. I have a data frame in wide format with ~ 200 trials (column-wise) for each participant (row-wise). I now need to compute a variable for each trial, indicating whether the participant saw a target or a control

I wrote the code for one such trial:

data_final$target.41 <- ifelse(data_final$word_position.41 == 1 & data_final$line_position.41 == "left" | data_final$word_position.41 == 2 & data_final$line_position.41 == "right" , 1, 0)

This works, giving me a column with 1 and 0 depending on what the participants saw in this trial. (the 41 indicates the 41st trial)

Now i want to use a slope to do this for all trials dynamically.

However, my poor try doesn't work at all:

target.i <- NULL

temp <- NULL

for (i in 41:281) { 
    temp <- ifelse(data_final$word_position.i == 1 & data_final$line_position.i == "left" | data_final$word_position.i == 2 & data_final$line_position.i == "right" , 1, 0)
    target.i <- rbind(target.i,temp)
}
data_final <- cbind(data_final,target.i)
1

1 Answers

0
votes

The problem here is that variable name like word_position.i won't loop with i. You can do something like this:

target <- data.frame(matrix(nrow = dim(data_final)[1], ncol = 0))
for (i in 41:281) { 
    word_position.i <- paste("word_position.", i, sep = "")
    line_position.i <- paste("line_position.", i, sep = "")
    target.i <- paste("target.", i, sep = "")
    temp <- ifelse(data_final[,word_position.i] == 1 & data_final[,line_position.i] == "left" | data_final[,word_position.i] == 2 & data_final[,line_position.i] == "right" , 1, 0)
    target[,target.i] <- temp
}
data_final <- cbind(data_final,target)