'Error in R using imputed data : Error in `[<-.data.frame`(`*tmp*`, j, value = c() replacement has 165 rows, data has 163

I am trying to add a column in an imputed dataset (I used mice). I managed to transform the imputed dataset in a dataframe, add the column that comes from another dataset, merging the two datasets by ID number, and then creating a new column (smallestagegap_5ok), but then when I try to transform the dataframe back to the mice format, I get an error message. I usually have no problems doing this. The original dataset and the dataset with the additional columns have the same number of rows, with just 2 column more in the second case. Any input would be valuable, thanks!

elfe_mids <- load.Rdata2("ALL_elfe_ecole_imp/ALL_elfe_ecole_imp.Rdata", path=getwd())


test <- complete(elfe_mids,"long",include=T)
test2 <- test

age <- as.data.frame(cbind(database$id_Dem724_490_HP, database$A05R_AGE_1))
colnames(age)=c("id_Dem724_490_HP", "age")

test2 <- merge(test2,age, by="id_Dem724_490_HP" , all.x=TRUE)
test2$smallestagegap_5ok <- as.numeric(abs(test2$smallestagegap_5 - test2$age))

test2 <- as.data.frame(test2)

elfe_mids <- as.mids(test2)

Output:

Error in `[<-.data.frame`(`*tmp*`, j, value = c(0.4090080740378, -0.564495355228495,  : 
  replacement has 165 rows, data has 163


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source