This will be a much simpler sentence if you are dealing with character variables, not factors .
I will introduce a simple solution to data.table (for an elegant and easy-to-use syntax among many other benefits)
x <- data.frame(c1=letters[1:26],c2=letters[26:1], stringsAsFactors =FALSE) x[x$c1 == "m","c2"] <- NA y <- data.frame(c1="m",c2="n", stringsAsFactors = FALSE) library(data.table) X <- as.data.table(x) Y <- as.data.table(y)
For ease of merging, I will create a column indicating
X[,missing_c2 := is.na(c2)]
i.c2 means that we use the values โโof c2 from argument i to [
This approach assumes that not all values โโin which c1 = 'm' are absent in X , and you do not want to replace all values โโin c2 with 'm' , where c1='m' are those that are not
Basic solution
Here is the basic solution - I use merging, so y data.frame may contain more missing replacements than necessary (i.e. it can have values โโfor all values โโof c1 , although only c1= m `` is required.
# add a second missing value row because to make the solution more generalizable x <- rbind(x, data.frame(c1 = 'm',c2 = NA, stringsAsFactors = FALSE) ) missing <- x[is.na(x$c2),] merged <- merge(missing, y, by = 'c1') x[is.na(x$c2),] <- with(merged, data.frame(c1 = c1, c2 = c2.y, stringsAsFactors = FALSE))
If you use factors , you will come across a wall of pain to match levels.