R - 根据匹配值从另一个数据框中添加数据
R - Add data from another dataframe based on matching values
我有 2 个这样的数据框:
x1= c("Station 1", "Station 3", "Station 4")
x2= c(1, 4, 2)
df1 = data.frame(Station=x1, Number=x2)
x1= c("Station 1", "Station 2", "Station 3", "Station 4", "Station 5", "Station 6")
x2= seq(-2,10 , length=6)
x3= seq(30, 45, length=6)
x4= seq(1, 16, length=6)
x5= seq(4, 16, length=6)
df2 = data.frame(Station=x1, Lon=x2, Lat=x3, Area=x4, Mis=x5)
> df1
Station Number
1 Station 1 1
2 Station 3 4
3 Station 4 2
> df2
Station Lon Lat Area Mis
1 Station 1 -2.0 30 1 4.0
2 Station 2 0.4 33 4 6.4
3 Station 3 2.8 36 7 8.8
4 Station 4 5.2 39 10 11.2
5 Station 5 7.6 42 13 13.6
6 Station 6 10.0 45 16 16.0
对于我在 df1 中的 3 个站,我想从第二个数据帧中提取数据(对于 Lon、Lat 和 Area)。所以我想将 Lon、Lat 和 Area 添加到站 1、3 和 4 的 df1。
我希望它看起来像这样:
> dfnew
Station Number Lon Lat Area
1 Station 1 1 -2.0 30 1
2 Station 3 4 2.8 36 7
3 Station 4 2 5.2 39 10
有人可以帮忙吗?
使用dplyr
:
library(dplyr)
df_new <- inner_join(df1, df2, by = "Station")
df_new$Mis <- NULL
df_new:
Station Number Lon Lat Area
1 Station 1 1 -2.0 30 1
2 Station 3 4 2.8 36 7
3 Station 4 2 5.2 39 10
我有 2 个这样的数据框:
x1= c("Station 1", "Station 3", "Station 4")
x2= c(1, 4, 2)
df1 = data.frame(Station=x1, Number=x2)
x1= c("Station 1", "Station 2", "Station 3", "Station 4", "Station 5", "Station 6")
x2= seq(-2,10 , length=6)
x3= seq(30, 45, length=6)
x4= seq(1, 16, length=6)
x5= seq(4, 16, length=6)
df2 = data.frame(Station=x1, Lon=x2, Lat=x3, Area=x4, Mis=x5)
> df1
Station Number
1 Station 1 1
2 Station 3 4
3 Station 4 2
> df2
Station Lon Lat Area Mis
1 Station 1 -2.0 30 1 4.0
2 Station 2 0.4 33 4 6.4
3 Station 3 2.8 36 7 8.8
4 Station 4 5.2 39 10 11.2
5 Station 5 7.6 42 13 13.6
6 Station 6 10.0 45 16 16.0
对于我在 df1 中的 3 个站,我想从第二个数据帧中提取数据(对于 Lon、Lat 和 Area)。所以我想将 Lon、Lat 和 Area 添加到站 1、3 和 4 的 df1。
我希望它看起来像这样:
> dfnew
Station Number Lon Lat Area
1 Station 1 1 -2.0 30 1
2 Station 3 4 2.8 36 7
3 Station 4 2 5.2 39 10
有人可以帮忙吗?
使用dplyr
:
library(dplyr)
df_new <- inner_join(df1, df2, by = "Station")
df_new$Mis <- NULL
df_new:
Station Number Lon Lat Area
1 Station 1 1 -2.0 30 1
2 Station 3 4 2.8 36 7
3 Station 4 2 5.2 39 10