【问题标题】:Replace row values to the left of a row-specific column-index value in the same row将行值替换到同一行中特定行的列索引值的左侧
【发布时间】: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


【解决方案1】:

试试这个:

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']
}

【讨论】:

  • 工作。谢谢!
【解决方案2】:

这是set 来自data.table 的另一个选项

library(data.table)
setDT(def)
for(j in 0:3) {
  j1 <- grep(j, names(def))
  set(def, i = which(!is.na(def[[j1]]) & j < def$status.update.year),
                                   j = j1, value = "Active")
 }

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 2015-11-18
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多