考慮兩個資料框
df1 <- data.frame(a=LETTERS[1:6],
b=c("apple", "apple","dog", "red", "red","red"))
df2 <- data.frame(col1=c("apple", "golf", "dog", "red"),
col2=c("fruit", "sport","animal", "color"))
> df1
a b
1 A apple
2 B apple
3 C dog
4 D red
5 E red
6 F red
> df2
col1 col2
1 apple fruit
2 golf sport
3 dog animal
4 red color
我想創建
> output
a b
1 A fruit
2 B fruit
3 C animal
4 D color
5 E color
6 F color
我使用基本的 for 回圈得到了我正在尋找的輸出。但是有沒有什么巧妙的方法可以通過 dplyr 的管道來實作呢?
for(i in 1:nrow(df1)){
df1[i,2] <- df2[df2$col1==df1[i,2], 2]
}
uj5u.com熱心網友回復:
使用聯接
library(dplyr)
left_join(df1, df2, by = c("b" = "col1")) %>%
select(a, b = col2)
-輸出
a b
1 A fruit
2 B fruit
3 C animal
4 D color
5 E color
6 F color
or in base Rwith matchor named 向量
df1$b <- setNames(df2$col2, df2$col1)[df1$b]
uj5u.com熱心網友回復:
lapply與和的解決方案match:
df1$b <- unlist(lapply(df1$b, function(x) df2$col2[match(x, df2$col1)]))
df1
a b
1 A fruit
2 B fruit
3 C animal
4 D color
5 E color
6 F color
uj5u.com熱心網友回復:
df1$b <- df2[ df2$col1 == df1$b, 'col2' ]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/529905.html
標籤:r数据框dplyr
上一篇:基于R中的最大條件回填行
