gpt4 book ai didi

r:如何合并来自两个单独数据帧的组,前提是它们具有相同的内容

转载 作者:行者123 更新时间:2023-12-04 08:47:08 24 4
gpt4 key购买 nike

考虑一下我有两个数据集的例子(我的实际数据集更大):一个是人们被包含在群体中,另一个是人们被包含在房子里。
数据集 1:

Group   Person 
Group1 Andy
Group2 Andy
Group2 Richard
Group3 Richard
Group4 Andy
Group4 Richard
Group4 Meg
数据集 2:
House  Person
HouseA Andy
HouseA Richard
HouseB Andy
HouseB Richard
HouseB Meg
从这个例子中,可以看到 Group 2 和 House A 都包含 Andy 和 Richard。第 4 组和 B 组都包含安迪、理查德和梅格。我想要的输出是:
Group  House  Person
Group2 HouseA Andy
Group2 HouseA Richard
Group4 HouseB Andy
Group4 HouseB Richard
Group4 HouseB Meg
可重现的数据:
df1 <- structure(list(Group = c("Group1", "Group2", "Group2", "Group3", 
"Group4", "Group4", "Group4"), Names = c("Andy", "Andy", "Richard",
"Richard", "Andy", "Richard", "Meg")), class = "data.frame", row.names = c(NA,
-7L))

df2 <- structure(list(House = c("HouseA", "HouseA", "HouseB", "HouseB",
"HouseB"), Names = c("Andy", "Richard", "Andy", "Richard", "Meg"
)), class = "data.frame", row.names = c(NA, -5L))

最佳答案

dplyr的解决方案

library(dplyr)
merge (
df1 %>% group_by(Group) %>% mutate(nGroup = n()),
df2 %>% group_by(House) %>% mutate(nHouse = n())) %>%
filter(nGroup == nHouse) %>%
arrange(Group, House) %>%
select(Group, House, Names)

## Group House Names
##1 Group2 HouseA Andy
##2 Group2 HouseA Richard
##3 Group4 HouseB Andy
##4 Group4 HouseB Meg
##5 Group4 HouseB Richard

关于r:如何合并来自两个单独数据帧的组,前提是它们具有相同的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64258933/

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