我有一个不时包含值“0”的数据框。我需要检查这些值是否在另一个文件中可用,如果是,我需要它来替换 0。它有点难以解释,所以我将使用一个例子。
物品代码 | Section_A | Section_B |
---|---|---|
145 | 10000 | 100 |
165 | 15000 | 150 |
185 | 0 | 200 |
205 | 25000 | 0 |
如您所见,偶尔会有 0。另一方面,我为每个列标题都有单独的文件。我想编写一个 R 代码,如果值为 0,则存储该行的项目代码,搜索相应的列文件并查看是否存在真实值。
DF1 <- data.frame(ItemCode=c("145","165","185","205"),
Section_A=c("10000","15000","0","25000"),
Section_B=c("100","150","200","0"))
SectionA_File <- data.frame(ItemCode=c("145", "155","165","185", "195", "205"),
Tag=c("10000","3900", "15000","60000","9999","25000"))
SectionB_File <- data.frame(ItemCode=c("145", "155","165","185"),
Tag=c("100", "125", "150", "200"))
例如在DF1中,对于Section_A,ItemCode(185),值为0。我想调用一个命令来获取185的值并在SectionA_File中搜索它是“60000”。另一方面,在 DF1 中,Section_B, ItemCode(205) 不存在于 SectionB_File 中,因此将保留 0。谁能帮我解决这个问题?
期望的输出:
物品代码 | Section_A | Section_B |
---|---|---|
145 | 10000 | 100 |
165 | 15000 | 150 |
185 | 60000 | 200 |
205 | 25000 | 0 |
笨拙:
DF1 %>%
mutate(across(starts_with("Section"), ~ifelse(.==0, NA_character_, .))) %>%
rows_patch(SectionA_File %>% rename(Section_A = Tag), unmatched = "ignore") %>%
rows_patch(SectionB_File %>% rename(Section_B = Tag), unmatched = "ignore") %>%
mutate(across(starts_with("Section"), ~ifelse(is.na(.), 0, .)))
或:
DF1 %>%
left_join(SectionA_File, join_by(ItemCode)) %>%
left_join(SectionB_File, join_by(ItemCode)) %>%
transmute(
ItemCode,
SectionA = pmax(Section_A, Tag.x, na.rm = TRUE),
SectionB = pmax(Section_B, Tag.y, na.rm = TRUE)
)
结果
ItemCode Section_A Section_B
1 145 10000 100
2 165 15000 150
3 185 60000 200
4 205 25000 0