假設我有兩個起始資料框:
df1 <- data.frame(code1 = c("a", "b","z"), code2 = c("2", "3", "4"))
df2 <- data.frame(code1 = c("c", "o", "p"), code2 = c("2", "4", "5"),
column3 = "a", column4 = "b", column5 = "c")
我想通過“code2”列匹配兩個資料幀,如果匹配,請將 df1 中 code1 的值替換為 df2 中 code1 的值,以便最終資料幀如下所示:
df3<- data.frame(code1 = c("c", "b", "o"), code2 = c("2", "3", "4"))
uj5u.com熱心網友回復:
使用left_join和coalesce:
library(dplyr)
df1 %>%
left_join(df2[,c(1,2)], by = "code2") %>%
transmute(code1 = coalesce(code1.y, code1.x),
code2 = code2)
#> code1 code2
#> 1 c 2
#> 2 b 3
#> 3 o 4
uj5u.com熱心網友回復:
這是一個解決方案dplyr。據“查找”code1中df2,無論code2比賽; 當沒有找到匹配的,則默認為原code1在df1。
解決方案
library(dplyr)
# ...
# Code to generate 'df1' and 'df2'.
# ...
df1 %>% mutate(code1 = coalesce(
# Look up the 'code1' according to 'code2'...
df2$code1[match(code2, df2$code2)],
# ...and otherwise default to the original 'code1'.
code1
))
結果
給定df1,df2如你的例子
df1 <- data.frame(
code1 = c("a", "b","z"),
code2 = c("2", "3", "4")
)
df2 <- data.frame(
code1 = c("c", "o", "p"),
code2 = c("2", "4", "5"),
column3 = "a",
column4 = "b",
column5 = "c"
)
此解決方案應產生所需的結果:
code1 code2
1 c 2
2 b 3
3 o 4
筆記
使用match()而不是 a 的一個優點是dplyr::*_join():不需要額外的步驟來清除結果中的無關列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/408946.html
標籤:
