I have the following data.table, where each unique x
value is associated with a unique y
value. Then I force one x
value as NA
for purposes of the k-nearest neighbors exercise:
dt <- data.table(x = rep(c(1:4), 3),
y = rep(c("Brandon", "Erica", "Karyna", "Alex"), 3))
dt[3, 1] <- NA
print(dt)
# x y
#1: 1 Brandon
#2: 2 Erica
#3: NA Karyna
#4: 4 Alex
#5: 1 Brandon
#6: 2 Erica
#7: 3 Karyna
#8: 4 Alex
#9: 1 Brandon
#10: 2 Erica
#11: 3 Karyna
#12: 4 Alex
Referencing the first answer to this question, I created a binary matrix out of dt$y
as so:
dt.a <- model.matrix(~ y -1 , data = dt)
dt2 <- cbind(dt[, -2, with = FALSE], dt.a)
print(dt2)
# x yAlex yBrandon yErica yKaryna
#1: 1 0 1 0 0
#2: 2 0 0 1 0
#3: NA 0 0 0 1
#4: 4 1 0 0 0
#5: 1 0 1 0 0
#6: 2 0 0 1 0
#7: 3 0 0 0 1
#8: 4 1 0 0 0
#9: 1 0 1 0 0
#10: 2 0 0 1 0
#11: 3 0 0 0 1
#12: 4 1 0 0 0
Using the knnImpute
method from the preProcess
function of the caret
package, I would expect that the center-and-scaled output below of dt3[1, 3]
would equal rows 7 and 12. But it does not. In fact, it looks to be almost equal the negative value of rows 7 and 12.
preobj <- preProcess(dt2, method = "knnImpute")
dt3 <- predict(preobj, dt2)
print(dt3)
# x yAlex yBrandon yErica yKaryna
#1: -1.19857753 -0.5527708 1.6583124 -0.5527708 -0.5527708
#2: -0.37455548 -0.5527708 -0.5527708 1.6583124 -0.5527708
#3: -0.04494666 -0.5527708 -0.5527708 -0.5527708 1.6583124
#4: 1.27348863 1.6583124 -0.5527708 -0.5527708 -0.5527708
#5: -1.19857753 -0.5527708 1.6583124 -0.5527708 -0.5527708
#6: -0.37455548 -0.5527708 -0.5527708 1.6583124 -0.5527708
#7: 0.44946657 -0.5527708 -0.5527708 -0.5527708 1.6583124
#8: 1.27348863 1.6583124 -0.5527708 -0.5527708 -0.5527708
#9: -1.19857753 -0.5527708 1.6583124 -0.5527708 -0.5527708
#10: -0.37455548 -0.5527708 -0.5527708 1.6583124 -0.5527708
#11: 0.44946657 -0.5527708 -0.5527708 -0.5527708 1.6583124
#12: 1.27348863 1.6583124 -0.5527708 -0.5527708 -0.5527708
Shouldn't dt3$x
's row 3 equal rows 7 and 11? If so, what do I need to change in my script? If not, why?