代码之家  ›  专栏  ›  技术社区  ›  Essi

R-基于匹配值从另一个数据帧添加数据[重复]

  •  -1
  • Essi  · 技术社区  · 8 年前

    我有两个这样的数据帧:

     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)中提取数据。所以我想为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 回复  |  直到 8 年前
        1
  •  1
  •   sm925 user2788735    8 年前

    使用 dplyr :

    library(dplyr)      
    df_new <- inner_join(df1, df2, by = "Station")
    df_new$Mis <- NULL
    

    df\U新建:

         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