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
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