R选择 Dataframe 中按因子分组的两个最大值

bbmckpt7  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(97)

我有以下 Dataframe

v=c(1, 2, 3)
df <- data.frame(V1 = randomNumbers(n = 18,min = 0,max = 1, col=1),
                 factor_col = c(rep("A", 18)),
                 sessions = rep(v, each=6))

v=c(1, 2, 3, 4, 5, 6, 7, 8)
df2 <- data.frame(V1 = randomNumbers(n = 24,min = 0,max = 1, col=1),
                  factor_col = c(rep("B", 24)),
                  sessions = rep(v, each=3))

v=c(1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12)
df3 <- data.frame(V1 = randomNumbers(n = 33,min = 0,max = 1, col=1),
                  factor_col = c(rep("C", 33)),
                  sessions = rep(v, each=3))

Table = bind_rows(df, df2)
Table = bind_rows(Table, df3)

字符串
如何筛选factor_col的每个因子sessions的两个最大值,并计算V1在这两个激光会话中的平均值(每个factor_col)?
谢谢你,谢谢

ccrfmcuu

ccrfmcuu1#

IIUC:

Table %>% distinct(factor_col, sessions)  %>% group_by(factor_col) %>% 
  slice_max(n = 2, order_by = sessions) %>% left_join(Table) %>%
  group_by(sessions, factor_col) %>% summarise(v1_mean = mean(V1))

# sessions factor_col v1_mean
# <dbl> <fct>        <dbl>
# 1        2 A            0.5  
# 2        3 A            0.333
# 3        7 B            0.667
# 4        8 B            0    
# 5       11 C            0.667
# 6       12 C            0.667

字符串

相关问题