R从矢量中插入周数,然后执行na.locf



对于类似于下面的数据帧(但显然要大得多(,我想从向量中添加缺失的周数(向量在下面命名为周(。最后,var1的每个值应该有4行,由第40-42周组成,因此对于var1的不同值,为周插入的值可能不同。最初,插入的行可以具有值NA,但作为第二步,我希望对var1的每个值执行na.locf。有人知道怎么做吗?

数据帧示例:

dat <- data.frame(var1 = rep(c('a','b','c','d'),3),
week = c(rep(40,4),rep(41,4),rep(42,4)),
value = c(2,3,3,2,4,5,5,6,8,9,10,10))
dat <- dat[-c(6,11), ]
weeks <- c(40:42)

这样?

dat %>% 
tidyr::complete(var1,week) %>% 
group_by(var1) %>% 
arrange(week) %>% 
tidyr::fill(value)
# A tibble: 12 x 3
# Groups:   var1 [4]
var1   week value
<fct> <dbl> <dbl>
1 a        40     2
2 a        41     4
3 a        42     8
4 b        40     3
5 b        41     3
6 b        42     9
7 c        40     3
8 c        41     5
9 c        42     5
10 d        40     2
11 d        41     6
12 d        42    10
你好,你考虑过tidyr::complete和dplyr::fill((吗。
library(dplyr)
library(tidyr)
complete(dat, week = 40:42, var1 = c("a", "b", "c", "d")) %>% fill(value, .direction = 
"down")

最新更新