在 R 中,我如何轻松找到表中变量的前 x 个实例,最好使用 dplyr?

问题描述 投票:0回答:1

我有以下数据框

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 个实例。谢谢!

r sorting mean
1个回答
0
投票

找到解决办法了

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)

© www.soinside.com 2019 - 2024. All rights reserved.