【发布时间】:2020-02-28 19:53:32
【问题描述】:
我想通过 for 循环使用 dplyr 将我的每个独立变量(列)与我的目标变量进行汇总。这是我的主要数据框:
contract_ID Asurion 变量_1 变量_2 变量_3
1 年 a c f
2 年
3 N b c g
4 N a d f
5 岁 b c f
6 年
分组后我得到
a1 <- a %>%
group_by(Asurion,BhvrBnk_Donates_to_Env_Causes) %>%
summarise(counT=n_distinct(CONTRACT_ID)) %>%
mutate(perc=paste0(round(counT/sum(counT)*100,2),"%"))
Asurion Variable_1 CounT perc
Y a 3 75%
Y b 1 25%
N a 1 50%
N b 1 50%
我想对我的数据框中的每个变量进行总结,我想使用 for 循环来完成。我如何达到我想要的结果
这是我尝试使用的,但它似乎不起作用。这是一个学校项目,我需要为此使用 for 循环。请帮我看看这里
categorical <- colnames(a)###where categroical is the names of all columns in a
###I would like to have a for loop for every column in a and summarise in the following way. I would like to store each of the summarisations in a separate dataframe
for (i in categorical) {
a[[i]] <- a %>%
group_by(Asurion,get(i)) %>%
summarise(counT=n_distinct(CONTRACT_ID)) %>%
mutate(perc=paste0(round(counT/sum(counT)*100,2),"%"))
}
【问题讨论】:
-
根据您的 cmets,您能否还包括预期的输出?这似乎是一个 xy 问题,如果您指出最终输出,人们可能会有不同的方法
标签: r for-loop group-by dplyr summarize