r - 如何将一列的 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 不是一种有效的方法。
解决方案
我们可以fill
从tidyr
包中使用。
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
推荐阅读
- javascript - 在什么情况下 'a != a' 在 JavaScript 中解析为 true?
- reactjs - Ngrok 不断与 Nextjs 重新连接
- certificate - 为什么 NET::ERR_CERT_COMMON_NAME_INVALID 在 admin.localhost 上出现 chrome 错误,SAN 和 CN 设置为 *.localhost
- android - 如何每天重置计步器?
- http - 可以利用 Content-length 标头吗?
- android - Android loadThumbnail 专辑插图 (API 29)
- javascript - 屏幕共享不适用于 getDisplayMedia
- r - 为 POSIXct 日期格式添加因子列
- php - 找不到常量 subresourceOperations,类 App\Entity\Comment
- python - 有没有办法利用 asyncio 的多个 CPU 内核?