In my previous question, I needed to create a new column according to values in another column. In that question, values in expected_result is only updated when there is a CS+ in stimulus column. What I am trying to do now is to only update the value after there is a new CS+. Expected results are as shown in figure 1. For instance, in the second CS+, the value is still 30, it is only updated to 36 in the next trial.
Figure 1
Example data
structure(list(subject = c("subject1", "subject1", "subject1",
"subject1", "subject1", "subject1", "subject1", "subject1", "subject1",
"subject2", "subject2", "subject2", "subject2", "subject2", "subject2",
"subject2", "subject2", "subject2"), stimulus = c("CS-", "CS-",
"CS+", "CS-", "S8", "S7", "S2", "CS+", "CS+", "CS-", "CS-", "CS+",
"S4", "S9", "S7", "CS+", "CS+", "S8"), Per_size = c(60L, 70L,
30L, 85L, 62L, 56L, 42L, 36L, 34L, 24L, 21L, 70L, 65L, 31L, 35L,
79L, 79L, 34L), new_expect = c(30, 30, 30, 30, 30, 30, 30, 30,
36, 36, 36, 36, 70, 70, 70, 70, 79, 79)), row.names = c(NA, -18L
), class = c("data.table", "data.frame"))
Solution provided by @akrun for the previous question where values are updated on the CS+ trial.
df1[stimulus == 'CS+', New := Per_size]
df1[, New := nafill(nafill(New, type = 'locf'), type = 'nocb'), subject]
