Q: Adding values corresponding to matched column items I have two sample datasets which are as follows:
structure(list(CellType = structure(c(1L, 2L, 3L, 3L, 1L, 4L, 
4L), .Label = c("CellA", "CellB", "CellC", "CellD"), class = "factor"), 
    Gene1 = c(0.1, 0.2, 0.1, 0.3, 0.5, NA, NA), Gene2 = c(0.1, 
    0.2, 0.1, 0.3, 0.5, 0.2, 0.2), Gene3 = c(0.1, 0.2, 0.1, 0.3, 
    0.5, 0.5, 0.5)), class = "data.frame", row.names = c(NA, 
-7L))

And here is the second one:
structure(list(CellType = structure(c(1L, 1L, 2L, 3L, 4L), .Label = c("CellD", 
"CellX", "CellY", "CellZ"), class = "factor"), Gene1 = c(10L, 
20L, 20L, 30L, 10L), Gene2 = c(0.1, 0.2, 0.1, 0.3, 0.5), Gene3 = c(0.1, 
0.2, 0.1, 0.3, 0.5)), class = "data.frame", row.names = c(NA, 
-5L))

I would like to add items in 'Gene 1' column that match in 'Cell Type' column from the second data frame to the first one. In this case, only two cell type items match which are 'CellD'. Is there a way for me to add the corresponding values of '10' and '20' from the Gene 1 column of my second dataframe into my 'NA' fields in dataframe # 1?
Thanks!

A: In case they are sorted pmatch could be used. And you really only want to use CellType for matching.
i <- pmatch(x$CellType, y$CellType)
j <- !is.na(i)
x$Gene1[j] <- y$Gene1[i[j]]
#  CellType Gene1 Gene2 Gene3
#1    CellA   0.1   0.1   0.1
#2    CellB   0.2   0.2   0.2
#3    CellC   0.1   0.1   0.1
#4    CellC   0.3   0.3   0.3
#5    CellA   0.5   0.5   0.5
#6    CellD  10.0   0.2   0.5
#7    CellD  20.0   0.2   0.5

