問題描述
使用另一個數據框的條件創建一個新列 (Create a new column with a condition of another dataframe)
我有兩個 DF
df1
Zone Tarif
<dbl> <dbl>
1 1 0.125
2 2 0.217
3 3 0.307
4 4 0.387
5 5 0.449
6 6 0.580
7 7 0.684
8 8 0.894
和
df2
state total shipments koerier zone_shipments koerierkosten gewichtkoerier gewichtzone zone
AZ AZ 453 91 362 637 1092 702226.2 6
CA CA 2176 436 1740 3052 5232 2964741.2 5
ID ID 261 53 208 371 636 431186.9 2
MT MT 526 106 420 742 1272 485048.1 2
NV NV 265 53 212 371 636 484546.3 5
OR OR 410 82 328 574 984 591250.8 3
WA WA 521 105 416 735 1260 798673.8 1
我想在 df2 (df2$tarif
) 中創建一個帶有配對區域的新列和df1 的關稅值。示例:如果 df2$zone = 6 那麼 df2$tarif = 0.580(來自 df1 的信息)
預期輸出
df2
state total shipments koerier zone_shipments koerierkosten gewichtkoerier gewichtzone zone tarif
AZ AZ 453 91 362 637 1092 702226.2 6 0.580
CA CA 2176 436 1740 3052 5232 2964741.2 5 0.449
ID ID 261 53 208 371 636 431186.9 2 0.217
MT MT 526 106 420 742 1272 485048.1 2 0.217
NV NV 265 53 212 371 636 484546.3 5 0.449
OR OR 410 82 328 574 984 591250.8 3 0.307
WA WA 521 105 416 735 1260 798673.8 1 0.125
參考解法
方法 1:
We can use join
library(dplyr)
df2 %>%
left_join(df1, by = c("zone" = "Zone"))
Or with merge
from base R
merge(df2, df1, by.x = 'zone', by.y = 'Zone', all.x = TRUE)
方法 2:
We can use merge
for this:
df2 <‑ merge(df2, df1, by.x = "Zone")
(by Timo V、akrun、lab_rat_kid)