数据表按寿命显示了项目状态报告:
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"
但是"Distressed"
据报道,在第3年开始的一个项目是"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) })
如何将这些值替换"Active"
为每行特定的值status.update.year
?
试试这个:
library(data.table)
def = data.table(def)
for (y in 0:3) {
v = paste0('year.',y)
def[!is.na(get(v)) & y < status.update.year, (v):= 'Active']
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句