I am a new R user and I have been trying to execute an if statement nested within a for loop in order to code a new variable. I have a data.frame where some guys previously forgot to code the "condition" variable (factor with 3 levels: old,new,lure) from E-prime. The task has two phases encoding/retrieval (Block 1 and 2), two set of images (A and B) and a unique Word ID.
So I have this:
phase <- rep(c("Block1", "Block2"), each = 7)
condition <- rep(NA, times = 14)
setAorB <- rep(c("A", "B"), times = c(9,5))
WordID <- c(23,34,56,76,45,88,99,23,34,56,76,45,100,105)
loris_data <- data.frame(phase,condition,setAorB,WordID)
which gives me:
> loris_data
phase condition setAorB WordID
1 Block1 NA A 23
2 Block1 NA A 34
3 Block1 NA A 56
4 Block1 NA A 76
5 Block1 NA A 45
6 Block1 NA A 88
7 Block1 NA A 99
8 Block2 NA A 23
9 Block2 NA A 34
10 Block2 NA B 56
11 Block2 NA B 76
12 Block2 NA B 45
13 Block2 NA B 100
14 Block2 NA B 105
What I would like to achieve is: At retrieval (Block2), if setAorB is "A", then condition is "old". I tried this basic loop but, obviously, worked only for the old items given that it does not discriminate lures vs new items.
for(i in 1:length(loris_data$condition)) {
if(loris_data$setAorB[i] == "A") {
loris_data$condition[i] <-"old"}
else {
loris_data$condition[i] <- "new"
}
}
Then, I would like to say: if setAorB is "B" and the Word ID is the same of A (which means that are lures), then the condition is "lure", otherwise if setAorB is "B" but it has a unique WordID, the the condition is "new".
This would be the expected output:
> loris_data
phase condition setAorB WordID
1 Block1 <NA> A 23
2 Block1 <NA> A 34
3 Block1 <NA> A 56
4 Block1 <NA> A 76
5 Block1 <NA> A 45
6 Block1 <NA> A 88
7 Block1 <NA> A 99
8 Block2 old A 23
9 Block2 old A 34
10 Block2 lure B 56
11 Block2 lure B 76
12 Block2 lure B 45
13 Block2 new B 100
14 Block2 new B 105
Can anyone help with this code as I am still learning and I am struggling quite a lot?
library(data.table); setDT(loris_data)[phase == "Block2", condition := c('new', 'old', 'lure')[as.integer(factor(1 + 2*(setAorB == "A") + 4 * (setAorB == "B" & WordID %in% loris_data$WordID[loris_data$setAorB=="A"])))] ]convert the column condition to character or usecondition <- rep(NA_character_, times = 14)