一種可能的方法是使用match
功能。
d <- data.frame(id = rep(1:3, 2),
month = rep(1:2, each=3),
price1 = c(NA, 4, NA, 6, NA, NA),
price2 = c(2, NA, NA, NA, NA, 4))
d[is.na(d$price1), "price1"] <-
d[!is.na(d$price1), ][match(d[is.na(d$price1), "month"],
d[!is.na(d$price1), "month"]), "price1"]
d[is.na(d$price2), "price2"] <-
d[!is.na(d$price2), ][match(d[is.na(d$price2), "month"],
d[!is.na(d$price2), "month"]), "price2"]
> d
id month price1 price2
1 1 1 4 2
2 2 1 4 2
3 3 1 4 2
4 1 2 6 4
5 2 2 6 4
6 3 2 6 4
注意,如果有一個以上的非缺失值可供選擇,此方法將使用第一個非缺失值。
至於建議的Laterow,您可以遍歷變量:
for (j in 3:ncol(d)) {
varname <- names(d)[j]
d[is.na(d[, varname]), varname] <-
d[!is.na(d[, varname]), ][match(d[is.na(d[, varname]), "month"],
d[!is.na(d[, varname]), "month"]),
varname]
}
謝謝,我要試試這個! –