【发布时间】:2018-05-22 11:33:08
【问题描述】:
我有一个包含 40 行和 10 列的数据框。如果行的索引小于 17,我想派生一列,新列称为预测等于“值”列。我的意思是:
ID Year Value
1 2016 114235
2 2016 114235
3 2016 114235
4 2016 114235
5 2016 114235
然后:
ID Year Value Prediction
1 2016 114235 114235
2 2016 114235 114235
3 2016 114235 114235
4 2016 114235 114235
5 2016 114235 114235
我尝试编码如下,新列的所有行都是“NA”。
newdata$Prediction <- ifelse(nrow(newdata) <= 17, newdata$Value, NA)
newdata$Prediction <- lapply(newdata, function(x) ifelse(nrow(newdata) <= 17, newdata$Value, NA))
它不起作用。我该怎么做?
【问题讨论】:
-
df$Prediction <- NA; df$Prediction[1:17] <- df$Value[1:17]?
标签: r if-statement dataframe sapply