英文:
R select the two max values in dataframe grouped by factor
问题
我有以下的数据框:
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
呢?
英文:
I have the following 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)
how do I filter for the two max values of sessions
per each factor of factor_col
and calculate the average of V1
across those lase two sessions, for each factor_col
?
Thanks!
答案1
得分: 1
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
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论