Paul
Paul

Reputation: 107

Sum of lag functions

Within one person's data from a behavioral task, I am trying to sum the clock time at which a target appears (data$onset) and the reaction time of their response (data$Latency) to find the clock time at which they entered their response at. For future data processing reasons, these calculated values will have to be placed in the data$onset column two values down from when the target appeared on the screen. In the example below:

Item onset Latency
Prime 9.97 0
Target 10.70 0.45
Mask 11.02 0
Response NA 0

Onset is how many seconds into the task the stimuli appeared, and latency is reaction time to the target. latency for non-targets will always be 0, as subjects don't respond to them. in the "NA" under onset, I need that value to be the sum of the onset of the target+reaction time to the target (10.70+0.45). Here is the code I have tried:

data$onset=if_else(is.na(data$onset), sum(lag(data$onset, n = 2)+lag(data$Latency, n = 2)), data$onset)

If any clarification is needed please let me know.

Upvotes: 1

Views: 90

Answers (1)

Samet Sökel
Samet Sökel

Reputation: 2670

since you used if_else I'm adding a dplyr solution;

library(dplyr)

data %>%
mutate(onset=ifelse(is.na(onset),lag(onset,n =2)+lag(Latency,n = 2),onset))

output;

  Item     onset Latency
  <fct>    <dbl>   <dbl>
1 Prime     9.97    0   
2 Target   10.7     0.45
3 Mask     11.0     0   
4 Response 11.1     0   

Also note that, if you want to stick to your own syntax;

data$onset=if_else(is.na(data$onset), lag(data$onset, n = 2)+lag(data$Latency, n = 2), data$onset)

Upvotes: 1

Related Questions