复制上一行R中某行的值

Copy the value of a row in the previous row R

我有一个大数据集df;它的简短版本如下所示:

Time    Block   Accuracy
6087.8  Run2    NA
633.2   Run2    NA
547     Run2    incorrect
135.2   Run2    NA
6217.6  Run2    NA
175.2   Run2    NA
179     Run2    incorrect

我想复制 df$Accuracy 前一行的值 不正确,所以它看起来像这样:

Time    Block   Accuracy
6087.8  Run2    NA
633.2   Run2    incorrect
547     Run2    incorrect
135.2   Run2    NA
6217.6  Run2    NA
175.2   Run2    incorrect
179     Run2    incorrect

最有效的方法是什么?

要查看将受影响的行,运行:

which(df$Accuracy == "incorrect")-1 

which() returns 向量中对特定布尔语句为真的元素(在本例中,Accuracy 的值等于不正确)。然后我们从向量中的每个值中减去 1 以获得前一行的位置。

然后我们可以修改它们:

df[which(df$Accuracy == "incorrect")-1, "Accuracy"] <- "incorrect"

这会找到上面的所有行,并表示:对于这些行和列 "Accuracy",将值替换为 "incorrect"。

而不是硬编码 "incorrect" ,您可以只在每个 NA 下面设置值以向上移动。

na_bool = is.na(df$Accuracy)
df[na_bool,]$Accuracy = df[c(FALSE,na_bool[-length(na_bool)]),]$Accuracy