一种可能的方法是使用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]
}
谢谢,我要试试这个! –