r - 如何比较两个不同 DF 中的两列,并在另一列中添加值?
问题描述
我有两个不同的 DF (caracteristica_receita
和coop_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")
解决方案
感谢你们 !工作!
另外,我的朋友也发了这个答案:
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
太感谢了 !
推荐阅读
- python - scrapy向Mysql插入数据
- c# - 在 DataGridView 中显示 WebServe 的 xml 结果
- scala - Spark Scala:使用 $ 的符号的功能差异?
- python - 使用 Python 提取页面源
- kubernetes - kubectl -f 缩写
- c# - 比较 typeof(Dictionary) 时出错,因为 Dictionary`2
- huawei-mobile-services - 华为 AdsKit `AdParam.Builder` 的允许值是多少?
- python - 检查目标时出错:预期 x3 有 2 个维度,但得到了形状为 (30, 1, 4) 的数组
- build - 为什么要使用`config.status --recheck`?– 因为它不会*保存*任何东西
- c - C: 处理案例...else