以下是一些示例数据:
dat <- data.frame(col0 = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
col1 = c(NA, 100, 100, NA, 200, 200, NA, 300, 300),
col2 = c(1, 2, 3, 1, 2, 3, 1, 2, 3))
当col2=1时,我想更改col1中的任何NA值,使用col1中NA后面的值。
我能想到的最好的是
dat <- dat %>%
mutate(col1 = replace(col1, which(is.na(col1) &
col2 == 1), 100))
但我不知道如何获得col1…的下一个值
理想情况下,解决方案将使用tidyverse。
我的实际数据集相当大,所以用c(100200300(替换col1中的NA不是一种有效的方法。
我们可以使用tidyr
包中的fill
。
library(tidyr)
dat2 <- fill(dat, col1, .direction = "up")
dat2
# col0 col1 col2
# 1 1 100 1
# 2 1 100 2
# 3 1 100 3
# 4 2 200 1
# 5 2 200 2
# 6 2 200 3
# 7 3 300 1
# 8 3 300 2
# 9 3 300 3
使用na.locf
的选项
library(zoo)
dat$col1 <- na.locf(dat$col1, fromLast = TRUE)
dat$col1
#[1] 100 100 100 200 200 200 300 300 300