r - Select columns dynamically -


i'm new here , beginner @ r.

i'm struggling following problem. have data frame in wide format ~ 200 trials (column-wise) each participant (row-wise). need compute variable each trial, indicating whether participant saw target or control

i wrote code 1 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 column 1 , 0 depending on participants saw in trial. (the 41 indicates 41st trial)

now want use slope trials dynamically.

however, poor try doesn't work @ all:

target.i <- null  temp <- null  (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) 

the problem here variable name word_position.i won't loop i. can this:

target <- data.frame(matrix(nrow = dim(data_final)[1], ncol = 0)) (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) 

Comments