'Conditional row count based on two variables (R)
I have a problem I can't wrap my head around at the moment. I have a large dataframe that looks something like this:
df <- data.frame(
Marker = c("", "", "", "start_tone", "", "", "start_trial", "", "", "", "", "", "", "", "start_tone", "", "", "", "start_trial", "", "", "", "", "", ""),
size=c(3, NA, -1, -1, 4, -1, -1 , 3.5, -1, -1, 4, -1, -1, NA, 4, -1, -1, 2, -1, -1, -1, -1, -1, 4.5, -1))
df
What I want is to count the number of samples starting from the "start_trial" marker. I want that count to go both directions, in negative and positive values. Furthermore, I want that negative count to stop an n amount of samples (say 2) before the "start_tone" marker. In the positive direction, I want that count to stop n (here 2) samples before the next "start_tone" marker (where the negative count starts). Lastly, I want a new column that keeps track of the trials around each "start_trial" marker. So, it should look something like the following:
df2 <- data.frame(SampleCount = c("", -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6),
Marker = c("", "", "", "start_tone", "", "", "start_trial", "", "", "", "", "", "", "", "start_tone", "", "", "", "start_trial", "", "", "", "", "", ""),
size=c(3, NA, -1, -1, 4, -1, -1 , 3.5, -1, -1, 4, -1, -1, NA, 4, -1, -1, 2, -1, -1, -1, -1, -1, 4.5, -1),
trial=c("", "trial 1", "trial 1", "trial 1", "trial 1", "trial 1", "trial 1", "trial 1", "trial 1", "trial 1", "trial 1", "trial1", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2", "trial 2" ))
df2
Thanks a lot for helping out!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
