join matching columns in a data.frame or data.table

前端 未结 2 1454
难免孤独
难免孤独 2020-12-16 03:14

I have the following data.frames:

a <- data.frame(id = 1:3, v1 = c(\'a\', NA, NA), v2 = c(NA, \'b\', \'c\'))
b <- data.frame(id = 1:3, v1 = c(NA, \'B         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-16 03:50

    The type of merge you specify probably won't be possible using merge (with data frames), although saying that usually invites being proved wrong.

    You also omit some details: will there always be a single unique non-NA value in each column for each id value? If so, this will work:

    ab <- rbind(a,b)
    > colFun <- function(x){x[which(!is.na(x))]}
    > ddply(ab,.(id),function(x){colwise(colFun)(x)})
      id v1 v2
    1  1  a  A
    2  2  B  b
    3  3  C  c
    

    A similar strategy should work with data.tables as well:

    abDT <- data.table(ab,key = "id")
    > abDT[,list(colFun(v1),colFun(v2)),by = id]
         id V1 V2
    [1,]  1  a  A
    [2,]  2  B  b
    [3,]  3  C  c
    

提交回复
热议问题