首页 > 解决方案 > 如何比较两个不同 DF 中的两列,并在另一列中添加值?

问题描述

我有两个不同的 DF (caracteristica_receitacoop_receita_anos2d)。我需要比较其中的两列(CNPJ 和 ANO)。如果它们匹配,我需要在新列 ( caracteristica_receita$benford) 中添加“1”。

我一直在使用

caracteristica_receita$benford[which(caracteristica_receita$CNPJ %>%
                                       is.element(coop_receita_anos2d$CNPJ))] <- 1 

但我不知道如何将它用于两列。

caracteristica_receita <- structure(list(CNPJ = c(1234, 5678, 91012, 12346, 96385, 87952, 
7789, 2535, 4459, 5457), NOME_INSTITUICAO = c("XXXX", 
"AAAA", "BBBB", "CCCC", "DDDDD", 
"RRRR", "FFFFF", 
"GGGGG", "HHHHHH", 
"IIIIIII"), ano_fundacao = c(1993, 
1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994), ANO = c(2014, 
2015, 2014, 2015, 2016, 2014, 2014, 2015, 2016, 2017), benford = c(0, 0, 
    0, 0, 0, 0, 0, 0, 0, 0)), .Names = c("CNPJ", "NOME_INSTITUICAO", 
"ano_fundacao", "ANO", "benford"), row.names = c(NA, 10L), class = "data.frame")

coop_receita_anos2d <- structure(list(CNPJ = c(1234, 5678, 916862, 12346, 96385, 87952, 
7789, 2535, 4459, 46868), ANO = c(2014, 2014, 0, 0, 0, 2014, 
0, 0, 0, 0)), .Names = c("CNPJ", 
"ANO"), row.names = c(1L, 3L, 
7L, 11L, 15L, 19L, 23L, 27L, 31L, 35L), class = "data.frame")

所以,我想要:

structure(list(CNPJ = c(1234, 5678, 91012, 12346, 96385, 87952, 
7789, 2535, 4459, 5457), NOME_INSTITUICAO = c("XXXX", 
"AAAA", "BBBB", "CCCC", "DDDDD", 
"RRRR", "FFFFF", 
"GGGGG", "HHHHHH", 
"IIIIIII"), ano_fundacao = c(1993, 
1993, 1994, 1994, 1994, 1994, 1994, 1994, 1994, 1994), ANO = c(2014, 
2015, 2014, 2015, 2016, 2017, 2014, 2015, 2016, 2017), benford = c(1, 0, 
    0, 0, 0, 1, 0, 0, 0, 0)), .Names = c("CNPJ", "NOME_INSTITUICAO", 
"ano_fundacao", "ANO", "benford"), row.names = c(NA, 10L), class = "data.frame")

标签: rdataframejoin

解决方案


感谢你们 !工作!

另外,我的朋友也发了这个答案:

caracteristica_receita$benford[which(str_c(caracteristica_receita$CNPJ, caracteristica_receita$ANO) %>% 
                                    is.element(str_c(coop_receita_anos2d$CNPJ, coop_receita_anos2d$ANO)))] <- 1 

太感谢了 !


推荐阅读