transform(merge(df1, df2, all.x = TRUE), subs = data1 - data2)
sample data1 data2 subs
1 1 200 150 50
2 1 300 150 150
3 2 150 230 -80
4 2 300 230 70
5 2 250 230 20
6 3 200 260 -60
7 3 240 260 -20
8 4 180 200 -20
9 5 190 NA NA
10 n 200 200 0
df1 <- structure(list(sample = c("1", "1", "2", "2", "2", "3", "3",
"4", "5", "n"), data1 = c(300L, 200L, 150L, 300L, 250L, 200L,
240L, 180L, 190L, 200L)), class = "data.frame", row.names = c(NA,
-10L))
df2 <- structure(list(sample = c("1", "2", "3", "4", "n"), data2 = c(150L,
230L, 260L, 200L, 200L)), class = "data.frame", row.names = c(NA,
-5L))