R 如何将一列的NA值替换为该列后面的值?
以下是一些示例数据:R 如何将一列的NA值替换为该列后面的值?,r,R,以下是一些示例数据: 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)) dat我们可以使用tidyr包中的fill library(tidyr) dat2 <- fill(dat, col1, .direction
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))
dat我们可以使用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
library(tidyr)
dat2使用na.locf的选项
library(zoo)
dat$col1 <- na.locf(dat$col1, fromLast = TRUE)
dat$col1
#[1] 100 100 100 200 200 200 300 300 300
图书馆(动物园)
dat$col1
library(zoo)
dat$col1 <- na.locf(dat$col1, fromLast = TRUE)
dat$col1
#[1] 100 100 100 200 200 200 300 300 300