【发布时间】:2017-04-28 04:36:37
【问题描述】:
数据表按生命周期显示项目的状态报告:
def <- data.frame(c("ProjA", "ProjB", "ProjC"), c("0", "2", "2"),
c("Active", "Cancelled", "Distressed"), c("Active", NA, "Distressed"),
c("Active", "Cancelled", "Distressed"), c("Active", NA, "Distressed"), stringsAsFactors = FALSE)
colnames(def) <- c("proj.name", "status.update.year", "year.0", "year.1", "year.2", "year.3")
def$status.update.year <- as.numeric(def$status.update.year)
def
proj.name status.update.year year.0 year.1 year.2 year.3
1 ProjA 0 Active Active Active Active
2 ProjB 2 Cancelled <NA> Cancelled <NA>
3 ProjC 2 Distressed Distressed Distressed Distressed
status.update.year 变量记录从"Active" 更改为另一个状态的年份。
项目应该以 "Active" 开始,但在第 3 年成为 "Distressed" 的项目现在报告为在过去所有年份中的 "Distressed",这是有观察的。这个错误的回溯是我想要更正的。
我想将标记为“0”的列的行值更改为“3”,这样在状态更新年份之前,所有非 NA 观察在状态更改年份之前都标记为“活动”,结果像这样:
proj.name status.update.year year.0 year.1 year.2 year.3
1 ProjA 0 Active Active Active Active
2 ProjB 2 Active <NA> Cancelled <NA>
3 ProjC 2 Active Active Distressed Distressed
我可以找到每一行在最后一个非 NA 观测值之前的所有非 NA 观测值:
apply(def[ ,3:6], 1, function(x) { head(x[!is.na(x)], -1) })
当这些值位于每行特定的status.update.year 之前时,如何将这些值替换为"Active"?
【问题讨论】:
-
因此,如果我理解正确,您希望将年份为 status.update.year 的所有情况转换为
Active,但有 NA 的情况除外? -
是的,完全正确。
标签: r indexing dataframe replace