Merging two columns into one in R

后端 未结 7 921
情深已故
情深已故 2020-11-29 02:06

I have the following data frame, and am trying to merge the two columns into one, while replacing NA\'s with the numeric values.

ID    A     B
1         


        
7条回答
  •  星月不相逢
    2020-11-29 02:41

    Assuming either A or B have a NA, that would work just fine:

    # creating initial data frame (actually data.table in this case)
    library(data.table)
    x<- as.data.table(list(ID = c(1,2,3,4), A = c(3, NA, NA, 1), B = c(NA, 2, 4, NA)))
    x
    #   ID  A  B
    #1:  1  3 NA
    #2:  2 NA  2
    #3:  3 NA  4
    #4:  4  1 NA
    
    
    #solution
    y[,New := na.omit(c(A,B)), by = ID][,c("A","B"):=NULL]
    y
    #   ID New
    #1:  1   3
    #2:  2   2
    #3:  3   4
    #4:  4   1
    

提交回复
热议问题