Xử lý dữ liệu khuyết bằng Imputation trong R
Michal Oleszak
Machine Learning Engineer



Mô hình cho mỗi biến phụ thuộc vào kiểu biến:
Bù Height và Weight trong nhanes bằng mô hình tuyến tính:
library(simputation)
nhanes_imp <- impute_lm(nhanes, Height + Weight ~ .)
Kiểm tra xem chúng đã được bù chưa:
nhanes_imp %>%
is.na() %>%
colSums()
Age Gender Weight Height Diabetes TotChol Pulse PhysActive
0 0 32 30 1 85 32 26
Khởi tạo giá trị thiếu bằng hotdeck và lưu vị trí thiếu:
nhanes_imp <- hotdeck(nhanes)
missing_height <- nhanes_imp$Height_imp
missing_weight <- nhanes_imp$Weight_imp
Lặp qua Height và Weight 5 lần, bù tại các vị trí ban đầu bị thiếu:
for (i in 1:5) {
nhanes_imp$Height[missing_height] <- NA
nhanes_imp <- impute_lm(nhanes_imp, Height ~ Age + Gender + Weight)
nhanes_imp$Weight[missing_weight] <- NA
nhanes_imp <- impute_lm(nhanes_imp, Weight ~ Age + Gender + Height)
}
for (i in 1:5) {
nhanes_imp$Height[missing_height] <- NA
nhanes_imp <- impute_lm(nhanes, Height ~ Age + Gender + Weight)
nhanes_imp$Weight[missing_weight] <- NA
nhanes_imp <- impute_lm(nhanes, Weight ~ Age + Gender + Height)
}
diff_height <- c()
diff_weight <- c()
for (i in 1:5) {
nhanes_imp$Height[missing_height] <- NA
nhanes_imp <- impute_lm(nhanes, Height ~ Age + Gender + Weight)
nhanes_imp$Weight[missing_weight] <- NA
nhanes_imp <- impute_lm(nhanes, Weight ~ Age + Gender + Height)
}
diff_height <- c()
diff_weight <- c()
for (i in 1:5) {
prev_iter <- nhanes_imp
nhanes_imp$Height[missing_height] <- NA
nhanes_imp <- impute_lm(nhanes, Height ~ Age + Gender + Weight)
nhanes_imp$Weight[missing_weight] <- NA
nhanes_imp <- impute_lm(nhanes, Weight ~ Age + Gender + Height)
}
diff_height <- c()
diff_weight <- c()
for (i in 1:5) {
prev_iter <- nhanes_imp
nhanes_imp$Height[missing_height] <- NA
nhanes_imp <- impute_lm(nhanes, Height ~ Age + Gender + Weight)
nhanes_imp$Weight[missing_weight] <- NA
nhanes_imp <- impute_lm(nhanes, Weight ~ Age + Gender + Height)
diff_height <- c(diff_height, mapc(prev_iter$Height, nhanes_imp$Height))
diff_weight <- c(diff_weight, mapc(prev_iter$Weight, nhanes_imp$Weight))
}

Xử lý dữ liệu khuyết bằng Imputation trong R