gpt4 book ai didi

r - 双左加入 dplyr 以恢复值

转载 作者:行者123 更新时间:2023-12-02 06:56:16 28 4
gpt4 key购买 nike

我已经检查了这个问题,但找不到匹配的条目。

假设您有 2 个 DF:

df1:mode   df2:sex
1 1
2 2
3

还有一个 DF3,其中大多数组合都不存在,例如

mode | sex  | cases      
1 1 9
1 1 2
2 2 7
3 1 2
1 2 5

你想用 dplyr 获得所有组合(不存在的组合=0)来总结它:

  mode | sex  | cases      
1 1 11
1 2 5
2 1 0
2 2 7
3 1 2
3 2 0

如果您执行单个 left_join (left_join(df1,df3),您将恢复不在 df3 中的模式,但“性别”显示为“NA”,如果您执行 left_join(df2,df3),也是如此。

那么在 cases=0 的情况下,你如何做 both left join 来恢复所有缺失的组合呢?首选 dplyr,但 sqldf 是一个选项。

提前致谢,p。

最佳答案

tidyr 的开发版本 tidyr_0.2.0.9000 有一个名为 complete 的新功能,我前几天看到它似乎就是为此而制作的某种情况。

帮助页面说:

This is a wrapper around expand(), left_join() and replace_na that's useful for completing missing combinations of data. It turns implicitly missing values into explicitly missing values.

要添加 df3 的缺失组合并改为填充 0 值,您可以这样做:

library(tidyr)
library(dplyr)

df3 %>% complete(mode, sex, fill = list(cases = 0))

mode sex cases
1 1 1 9
2 1 1 2
3 1 2 5
4 2 1 0
5 2 2 7
6 3 1 2
7 3 2 0

您仍然需要group_bysummarise 以获得您想要的最终输出。

df3 %>% complete(mode, sex, fill = list(cases = 0)) %>%
group_by(mode, sex) %>%
summarise(cases = sum(cases))

Source: local data frame [6 x 3]
Groups: mode

mode sex cases
1 1 1 11
2 1 2 5
3 2 1 0
4 2 2 7
5 3 1 2
6 3 2 0

关于r - 双左加入 dplyr 以恢复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30807855/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com