R - 根据匹配值从另一个数据帧添加数据

时间:2018-01-18 19:13:45

标签: r dataframe extract

我有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个站,我想从第2个数据帧中提取数据(对于Lon,Lat和Area)。所以我想为第1,3和4站的df1添加Lon,Lat和Area。

我希望它看起来像这样:

> 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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

使用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
相关问题