我有以下数据框
ID <- c(1,1,1,1,1,1,1,2,2,2,2,2,2,2,2, 3,3,3,3,3,3, 3,3,3,3,3,3)
reversal = c('R0', 'R0', 'R0', 'R0', 'R1', 'R1', 'R1',
'R0', 'R0', 'R0', 'R0', 'R1', 'R1', 'R1', 'R1',
'R0', 'R0', 'R0', 'R0', 'R1', 'R1', 'R1', 'R1', 'R2', 'R2', 'R2', 'R2')
event <- c(0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 1, 1, 1, 0,
0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1)
RT = runif(27)
df <- data.frame(ID, reversal, event, RT)
并且我想为每个
ID
和每个reversal
识别/标记event
中0的前4个实例和1的前4个实例,这样我就可以计算平均RT对于 0 和 1 的前 4 个实例。谢谢!
找到解决办法了
library(dplyr)
# Step 1: Flag the first 4 instances of 0 and 1 for each ID and reversal
df <- df %>%
group_by(ID, reversal, event) %>%
mutate(event_instance = row_number()) %>%
ungroup()
# Flag only the first 4 instances of each event type
df$event_instance <- ifelse(df$event_instance <= 4, df$event_instance, NA)
# Step 2: Calculate the mean RT for these identified instances
mean_values <- df %>%
filter(!is.na(event_instance)) %>%
group_by(ID, reversal, event) %>%
summarise(mean_RT = mean(RT, na.rm = TRUE))
print(mean_values)