gpt4 book ai didi

R合并三个数据框而不形成笛卡尔积

转载 作者:行者123 更新时间:2023-12-04 23:50:23 25 4
gpt4 key购买 nike

我有以下数据框 a,b,c

Year<-rep(c("2002","2003"),1)
Crop<-c("TTT","RRR")
a<-data.frame(Year,Crop)

Year<-rep(c("2002","2003"),2)
ProductB<-c("A","A","B","B")
b<-data.frame(Year,ProductB)

Year<-rep(c("2002","2003"),3)
Location<-c("XX","XX","YY","YY","ZZ","ZZ")
c<-data.frame(Year,Location)

并且想让他们聚在一起。当我使用 merge函数我得到了不是我想要的笛卡尔积。
d<-merge(a,b,by="Year")
e<-merge(d,c,by="Year")

我希望数据框看起来像
Year   Crop    ProductB    Location
2002 TTT A XX
2002 NA B YY
2002 NA NA ZZ
2003 RRR A XX
2003 NA B YY
2003 NA NA ZZ

这可能吗?谢谢你的帮助

最佳答案

这是使用 data.table 的一种方法.

require(data.table) ## 1.9.2
# (1)
setDT(a)[, GRP := 1:.N, by=Year]
setDT(b)[, GRP := 1:.N, by=Year]
setDT(c)[, GRP := 1:.N, by=Year]
# (2)
merge(a, merge(b, c, by=c("Year", "GRP"),
all=TRUE), by=c("Year", "GRP"), all=TRUE)

# Year GRP Crop ProductB Location
# 1: 2002 1 TTT A XX
# 2: 2002 2 NA B YY
# 3: 2002 3 NA NA ZZ
# 4: 2003 1 RRR A XX
# 5: 2003 2 NA B YY
# 6: 2003 3 NA NA ZZ

  • (1) - setDT converts the data.frame to data.table and then we create a new column GRP by grouping by Year. With this, we've a unique combination of Year, Grp.
  • (2) - we merge on the two columns Year, GRP.

.N是一个内置变量,用于保存该组的行数。

关于R合并三个数据框而不形成笛卡尔积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23898589/

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