res <- merge(dat1,dat2, by=c("V1", "V2"),all=TRUE)
indx <- is.na(res[,3])
res[indx,3] <- res[indx,4]
res[indx,4] <- NA
res[is.na(res)] <- 0
# V1 V2 V3.x V3.y
#1 1 2 10 0
#2 1 8 10 0
#3 2 3 20 100
#4 3 4 30 45
#5 4 5 40 78
#6 5 1 50 0
#7 5 2 99 0
#8 6 1 60 0
#9 6 80 60 0
data
dat1 <- structure(list(V1 = structure(1:6, .Label = c("1", "2", "3",
"4", "5", "6"), class = "factor"), V2 = structure(c(2L, 3L, 4L,
5L, 1L, 1L), .Label = c("1", "2", "3", "4", "5"), class = "factor"),
V3 = structure(1:6, .Label = c("10", "20", "30", "40", "50",
"60"), class = "factor")), .Names = c("V1", "V2", "V3"), class = "data.frame", row.names = c(NA,
-6L))
dat2 <- structure(list(V1 = structure(1:6, .Label = c("1", "2", "3",
"4", "5", "6"), class = "factor"), V2 = structure(c(5L, 2L, 3L,
4L, 1L, 6L), .Label = c("2", "3", "4", "5", "8", "80"), class = "factor"),
V3 = structure(c(1L, 2L, 3L, 5L, 6L, 4L), .Label = c("10",
"100", "45", "60", "78", "99"), class = "factor")), .Names = c("V1",
"V2", "V3"), class = "data.frame", row.names = c(NA, -6L))
Convert the data columns to numeric
class before you try the above code
dat1[] <- lapply(dat1, function(x) as.numeric(as.character(x)))
dat2[] <- lapply(dat2, function(x) as.numeric(as.character(x)))