尝试在R中合并 Dataframe ,类似于VLOOKUP

j0pj023g  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(92)

我有两个 Dataframe ,DF和DFMap。我试图使用DFMap作为Map表,并合并内容以完成DF(类似于VLOOKUP逻辑)以创建DFPerge(代码如下)。我想要的表在下面的代码中显示为DFPerge。我试图使用以下方法创建:DFmerge〈- merge(DF,DFMap,by =“C_SHORT”,all.x = TRUE)但不工作?

C_SHORT <- c("100001", "100002","100003","100001", "100002","100003")
C_FULL <- c("Base 100001", "Base 100002","Base 100003","Base 100001", "Base 100002","Base 100003")
ACC_SHORT <- c("X", "Y", "Z","X", "Y", "Z")
ACC_FULL <- c("Base X", "Base Y", "Base Z","Base X", "Base Y", "Base Z")
Date <-c ("04/01/2022","04/01/2022","045/01/2022","05/01/2022","05/01/2022","05/01/2022")
Value <- c(60,100,50,80,65,75)
DF<-data.frame(C_SHORT, C_FULL,ACC_SHORT,ACC_FULL,Date,Value)

C_SHORT <- c("100001", "100002","100003")
COUNTRY <- c("UK", "China","Ireland")
COLOUR <- c("BLUE", "RED", "GREEN")
DFMap<-data.frame(C_SHORT, COUNTRY, COLOUR)

C_SHORT <- c("100001", "100002","100003","100001", "100002","100003")
COUNTRY1 <- c("UK", "China","Ireland","UK", "China","Ireland")
C_FULL1 <- c("Base 100001", "Base 100002","Base 100003","Base 100001", "Base 100002","Base 100003")
ACC_SHORT1 <- c("X", "Y", "Z","X", "Y", "Z")
ACC_FULL1 <- c("Base X", "Base Y", "Base Z","Base X", "Base Y", "Base Z")
Date1 <-c ("04/01/2022","04/01/2022","045/01/2022","05/01/2022","05/01/2022","05/01/2022")
COLOUR1 <- c("BLUE", "RED", "GREEN","BLUE", "RED", "GREEN")
Value1 <- c(60,100,50,80,65,75)
DFmerge<-data.frame(C_SHORT, COUNTRY1,C_FULL1,ACC_SHORT1,ACC_FULL1,Date1,COLOUR1,Value1)

DFm <- merge(DF, DFMap, by = "C_SHORT", all.x = TRUE)
njthzxwz

njthzxwz1#

如果只想保持DF的行顺序,可以使用match

cbind(DF, DFMap[match(DF$C_SHORT, DFMap$C_SHORT), -1])
#    C_SHORT      C_FULL ACC_SHORT ACC_FULL        Date Value COUNTRY COLOUR
#1    100001 Base 100001         X   Base X  04/01/2022    60      UK   BLUE
#2    100002 Base 100002         Y   Base Y  04/01/2022   100   China    RED
#3    100003 Base 100003         Z   Base Z 045/01/2022    50 Ireland  GREEN
#1.1  100001 Base 100001         X   Base X  05/01/2022    80      UK   BLUE
#2.1  100002 Base 100002         Y   Base Y  05/01/2022    65   China    RED
#3.1  100003 Base 100003         Z   Base Z  05/01/2022    75 Ireland  GREEN

如果列也需要符合预期,则需要将其定义为来自DFDFMap的列混合。

cbind(DF, DFMap[match(DF$C_SHORT, DFMap$C_SHORT), -1])[c(1,7,2:5,8,6)]
#    C_SHORT COUNTRY      C_FULL ACC_SHORT ACC_FULL        Date COLOUR Value
#1    100001      UK Base 100001         X   Base X  04/01/2022   BLUE    60
#2    100002   China Base 100002         Y   Base Y  04/01/2022    RED   100
#3    100003 Ireland Base 100003         Z   Base Z 045/01/2022  GREEN    50
#1.1  100001      UK Base 100001         X   Base X  05/01/2022   BLUE    80
#2.1  100002   China Base 100002         Y   Base Y  05/01/2022    RED    65
#3.1  100003 Ireland Base 100003         Z   Base Z  05/01/2022  GREEN    75

相关问题