组合R中具有不同行数的两个数据帧

这个问题在这里已经有了答案:

  • 如何加入(合并)数据框架(内部,外部,左侧,右侧)? 12个答案

  • df1 <- data.frame(wpt = c(1, "meditate", "meditate", 2,3,"meditate"), 
                  ID = c(1235, 4562, 0928,6351,3826,0835))
    df1$wpt <- as.character(df1$wpt)
    
    
    df2 <- data.frame(wpt = c(1,2,3), 
                  fuel = c(1235, 4562, 0928), 
                  distance = c(2,3,4))
    df2$wpt <- as.character(df2$wpt)
    
    
    library(dplyr)
    full_join(df1, df2, by = "wpt")
    

    不介意价值! 您始终可以重新排列这些列。

           wpt   ID fuel distance
    1        1 1235 1235        2
    2 meditate 4562   NA       NA
    3 meditate  928   NA       NA
    4        2 6351 4562        3
    5        3 3826  928        4
    6 meditate  835   NA       NA
    

    以下是围绕match()构建的非合并基础R解决方案:

    link[names(body)[-1L]] <- body[match(link[,1L],body[,1L]),-1L];
    link;
    ##       wpt   ID fuel distance
    ## 1       1 1235 2221    53927
    ## 2 mediate 4562   NA       NA
    ## 3 mediate 0928   NA       NA
    ## 4       2 6351 4821    48261
    ## 5       3 3826 8362    47151
    ## 6 mediate 0835   NA       NA
    

    数据

    link <- data.frame(wpt=c('1','mediate','mediate','2','3','mediate'),ID=c('1235','4562','0928'
    ,'6351','3826','0835'),stringsAsFactors=F);
    body <- data.frame(wpt=c(1L,2L,3L),fuel=c(2221L,4821L,8362L),distance=c(53927L,48261L,47151L)
    );
    

    我认为以下应该工作:

    library(data.table)
    setkey(link,wpt)
    setkey(body,wpt)
    merge(link,body,by="wpt",all.x=T)
    
    链接地址: http://www.djcxy.com/p/24911.html

    上一篇: Combine two data frames with different number of rows in R

    下一篇: match two columns with two other columns