I am creating two data frames and then merging them into a third:
dat <- data.frame(code = c("A11", "B22", "C33"),
age = c(NA, NA, 12),
sex = c(NA, NA, 2),
more = c(7, 4, 9),
stringsAsFactors = FALSE)
age.and.sex <- read.table(textConnection("
code age sex
A11 15 2
B22 10 1
"), header = TRUE, stringsAsFactors = FALSE)
joined <- merge(dat, age.and.sex, by="code", all.x=TRUE)
joined
code age.x sex.x more age.y sex.y
1 A11 NA NA 7 15 2
2 B22 NA NA 4 10 1
3 C33 12 2 9 NA NA
Now, when I try to copy values from the two new columns ("age.y", "sex.y") into the two old ones ("age.x", "sex.y"), this works for one column, but for the other I get a curious warning:
joined[is.na(joined$age.x)]$age.x <- joined$age.y
joined[is.na(joined$sex.x)]$sex.x <- joined$sex.y
Warning message:
In `[<-.data.frame`(`*tmp*`, is.na(joined$sex.x), value = list(code = c("A11", :
provided 5 variables to replace 4 variables
What is going on here?