循环遍历R中后续行中的NA值 [英] Loop over NA values in subsequent rows in R
问题描述
我想用上一个乘以标量(例如3)替换数据框第一列中的每个缺失值
I want to replace each missing value in the first column of my dataframe with the previous one multiplied by a scalar (eg. 3)
nRowsDf <- nrow(df)
for(i in 1:nRowsDf){
df[i,1] =ifelse(is.na(df[i,1]), lag(df[i,1])+3*lag(df[i,1]), df[i,1])
}
上面的代码没有给我一个错误,但也没有执行任何操作.
The above code does not give me an error but does not do the job either.
此外,有没有比编写循环更好的方法了?
In addition, is there a better way to do this instead of writing a loop?
更新和数据:
这里是数据示例.我想用上一个乘以标量(例如3)替换数据框第一列中的每个缺失值. NA值在随后的行中.
Here is an example of data. I want to replace each missing value in the first column of my dataframe with the previous one multiplied by a scalar (eg. 3). The NA values are in subsequent rows.
df <- mtcars
df[c(2,3,4,5),1] <-NA
IND <- is.na(df[,1])
df[IND,1] <- df[dplyr::lead(IND,1L, F),1] * 3
上面代码的最后一行逐行完成作业(我应该运行它4次以填充缺少的4行).如何为所有行一次?
The last line of the above code does the job row by row (I should run it 4 times to fill the 4 missing rows). How can I do it once for all rows?
推荐答案
您应提供的可复制数据:
reproducible data which YOU should provide:
df <- mtcars
df[c(1,5,8),1] <-NA
代码:
IND <- is.na(df[,1])
df[IND,1] <- df[dplyr::lag(IND,1L, F),1] * 3
- 因为您使用了滞后,所以我使用了滞后.您说的是上一个".因此,也许您想使用
lead
. - 如果缺少前导情况下的第一个值或滞后情况下的最后一个值,会发生什么情况. (这仍然是个谜)
- since you use lag I use lag. You are saying "previous". So maybe you want to use
lead
. - What happens if the first value in lead case or last value in lag case is missing. (this remains a mystery)
这篇关于循环遍历R中后续行中的NA值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!