我有一个像这样的数据框:
rel <- c(2, 5, NA, 3, 6)
year.in <- c(4, NA, 2, 3, 2)
year.out <- c(6, 7, NA, 5, 4)
year.1 <- c(NA, NA, NA, NA, NA)
year.2 <- c(NA, NA, NA, NA, NA)
year.3 <- c(NA, NA, NA, NA, NA)
year.4 <- c(NA, NA, NA, NA, NA)
year.5 <- c(NA, NA, NA, NA, NA)
df <- as.data.frame(cbind(rel, year.in, year.out, year.1, year.2, year.3,
year.4, year.5))
我想做的是用'rel'的值更新year.1 - year.5中的缺失值,但前提是:(year.in >= year.i AND year.out <= year.i) (我是 1:5)
专注于刚刚入学的那一年,我想出了这个:
for (i in 1:5) ifelse(df$year.in < i,
df[paste("year", i, sep= ".")]<- NA,
df[paste("year", i, sep= ".")]<- df["rel"])
但这只是将所有 year.i 变量替换为 rel 的值。
我有两个问题:
如何在提到的条件下使用“rel”值更新 year.i 变量?
在这里使用 if else 语句不好吗?
最好的,并提前感谢,
理查德