首页 > 解决方案 > 如何将一列的 NA 值替换为该列之后的值?

问题描述

以下是一些示例数据:

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(100, 200, 300) 替换 col1 中的 NA 不是一种有效的方法。

标签: r

解决方案


我们可以filltidyr包中使用。

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

推荐阅读