gpt4 book ai didi

r - 如何使用多列作为键合并两个数据框?

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

假设我有以下数据框:

DF1 <- data.frame("A" = rep(c("A","B"), 18),
"B" = rep(c("C","D","E"), 12),
"NUM"= rep(rnorm(36,10,1)),
"TEST" = rep(NA,36))

DF2 <- data.frame("A" = rep("A",6),
"B" = rep(c("C","D"),6),
"VAL" = rep(c(1,3),3))

*注:每个唯一的变量组合 ABDF2应该有一个唯一的 VAL .

对于每一行,我想替换 NATEST对应的值为 VALDF1如果列中的值 AA匹配和列中的值 BB匹配该行。否则,我会离开 TESTNA .如果不使用 match 循环遍历每个组合,我将如何做到这一点?

理想情况下,答案将扩展到两个数据框,其中包含许多要匹配的列。

最佳答案

# this is your DF1    
DF1 <- data.frame("A" = rep(c("A","B"), 18),
"B" = rep(c("C","D","E"), 12),
"NUM"= rep(rnorm(36,10,1)),
"TEST" = rep(NA,36))

#this is a DF2 i created, with unique A, B, VAL
DF2 <- data.frame("A" = rep(c("A","B"),3),
"B" = rep(c("C","D","E"),2),
"VAL" = rep(1:6))

# and this is the answer of what i assume you want
tmp <- merge(DF1,DF2, by=c("A","B"), all.x=TRUE, all.y=FALSE)
DF1[4] <- tmp[5]

关于r - 如何使用多列作为键合并两个数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29212691/

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