如何进行条件合并

问题描述 投票:0回答:1

我有2个数据帧,并且我正在尝试使用条件进行内部联接。我将显示一个示例来阐明我要执行的操作:

A
  cnumero cep numero bairro
1  124,35 124     35      K
2  375,NA 375     NA      L
3   NA,28  NA     28      M

B

  cnumero bairro XY
1  124,35      J  1
2  375,48      L  2
3  135,28      M  3

要合并的第一个条件是,如果A$cep != NAA$numero != NA,则使用列cnumero进行连接,否则使用列bairro进行连接,结果:

new_A
  cnumero cep numero XY
1  124,35 124     35  1
2  375,NA 375     NA  2
3   NA,28  NA     28  3

到目前为止,我所做的是使用此方法进行内部联接:A[A$cnumero %in% unique(B$cnumero),],因为在我的实际数据帧中,我在数据帧B中有重复的值。

编辑:我的数据示例

A = data.frame(cnumero=c("124,35", "375,NA", "NA,28"),cep = c(124, 375, NA), numero = c(35, NA, 28), bairro =  c("K", "L","M"))
B = data.frame(cnumero=c("124,35", "375,48", "135,28"), bairro =  c("J", "L","M"), XY = c(1, 2, 3))
new_A = data.frame(cnumero=c("124,35", "375,NA", "NA,28"),cep = c(124, 375, NA), numero = c(35, NA, 28), XY = c(1, 2, 3))
r join inner-join
1个回答
1
投票

以这种方式在基数R中的解决方案呢,分两个步骤,首先是第一个条件的连接,然后是第二个,最后是结果的汇总:

# the join with the first condition
A_1 <-  merge(A[!is.na(A$cep) & !grepl('NA',A$cnumero), ],B, by = 'cnumero')

# select the column you need
A_1 <- A_1[,c("cnumero", "cep","numero","XY")]

# join for the second condition
A_2 <-  merge(A[is.na(A$cep) | grepl('NA',A$cnumero), ],B, by = 'bairro')

# select columns you need
A_2 <- A_2[,c("cnumero.x", "cep","numero","XY")]

# rename the second part's columns
colnames(A_2) <- colnames(A_1)

# now the result 
new_A <- rbind(A_1,A_2)
new_A
  cnumero cep numero XY
1  124,35 124     35  1
2  375,NA 375     NA  2
3   NA,28  NA     28  3

# in case you need to remove the "temporary" tables
# remove(A_1, A_2)
© www.soinside.com 2019 - 2024. All rights reserved.