[英]For-loop to summarize and joining by dplyr
Here is my simplified df:这是我的简化 df:
GP_A <- c(rep("a",3),rep("b",2),rep("c",2))
GP_B <- c(rep("d",2),rep("e",4),rep("f",1))
GENDER <- c(rep("M",4),rep("F",3))
LOC <- c(rep("HK",2),rep("UK",3),rep("JP",2))
SCORE <- c(50,70,80,20,30,80,90)
df <- as.data.frame(cbind(GP_A,GP_B,GENDER,LOC,SCORE))
> df
GP_A GP_B GENDER LOC SCORE
1 a d M HK 50
2 a d M HK 70
3 a e M UK 80
4 b e M UK 20
5 b e F UK 30
6 c e F JP 80
7 c f F JP 90
I want to summarize the score by GP_A, GP_B, or other grouping columns which are not showing in this example.我想通过 GP_A、GP_B 或本示例中未显示的其他分组列来总结分数。 As the count of grouping columns might up to 50, I decided to use for-loop to summarize the score.
由于分组列的数量可能高达 50,因此我决定使用 for 循环来汇总分数。
The original method is summarizing the score with 1 group one by one:原来的方法是用1组一一总结得分:
GP_A_SCORE <- df %>% group_by(GP_A,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
GP_B_SCORE <- df %>% group_by(GP_B,GENDER,LOC) %>% summarize(SCORE=mean(SCORE))
...
What I want is using the for-loop like this (cannot run):我想要的是使用这样的 for 循环(无法运行):
GP_list <- c("GP_A","GP_B",...)
LOC_list <- c("HK","UK","JP",...)
SCORE <- list()
for (i in GP_list){
for (j in LOC_list){
SCORE[[paste0(i,j)]] <- df %>% group_by(i,j,GENDER) %>% summarize(SCORE=mean(SCORE))
}}
As in "group_by()", the variables are classified as character and here is the error shown:在“group_by()”中,变量被归类为字符,这里是错误显示:
Error: Column
I
,J
is unknown错误:
I
列、J
列未知
Is there any method to force R to recognize the variable?有什么方法可以强制 R 识别变量?
I am facing the same problem on the left_join of dplyr.我在 dplyr 的 left_join 上面临同样的问题。
Error is shown when I was doing something like: left_join(x,y,by=c(i=i))
inside a loop.当我在
left_join(x,y,by=c(i=i))
执行以下操作时显示错误: left_join(x,y,by=c(i=i))
。
You could get the data in long format and then calculate the mean
你可以得到长格式的数据,然后计算
mean
library(dplyr)
library(tidyr)
df %>%
pivot_longer(cols = starts_with('GP')) %>%
group_by(GENDER ,LOC, name, value) %>%
summarise(SCORE = mean(SCORE))
# GENDER LOC name value SCORE
# <fct> <fct> <chr> <fct> <dbl>
# 1 F JP GP_A c 85
# 2 F JP GP_B e 80
# 3 F JP GP_B f 90
# 4 F UK GP_A b 30
# 5 F UK GP_B e 30
# 6 M HK GP_A a 60
# 7 M HK GP_B d 60
# 8 M UK GP_A a 80
# 9 M UK GP_A b 20
#10 M UK GP_B e 50
We can use melt
from data.table
我们可以用
melt
从data.table
library(data.table)
melt(setDT(df), measure = patterns("^GP"))[, .(SCORE = mean(SCORE)),
.(GENDER, LOC, variable, value)]
df <- data.frame(GP_A,GP_B,GENDER,LOC,SCORE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.