将观察值按组向前 n 行
Carry observations forward n rows by group
我有这样的数据,按 'orgid':
分组
orgid date type counter
12345 1-1-17 sale 3
12345 1-2-17 NA NA
12345 1-3-17 NA NA
78945 1-1-17 NA NA
78945 1-2-17 free 2
78945 1-3-17 NA NA
对于每个 'orgid',我想 "drag down" 'type' N-1 行,其中 N 由 'counter' 列定义。结果应如下所示:
orgid date type counter
12345 1-1-17 sale 3
12345 1-2-17 sale NA
12345 1-3-17 sale NA
78945 1-1-17 NA NA
78945 1-2-17 free 2
78945 1-3-17 free NA
我相信我可以使用zoo
包中的na.locf
,但我一直无法破解密码。有什么想法吗?
我不认为你可以为此使用 zoo::na.locf
,我不认为它是一个限制因素。(感谢 Henrik 让我直截了当!)
两个解决方案,我相信 data.table
大师可以添加相关的第三个:
基础 R
do.call("rbind.data.frame",
lapply(split(dat, cumsum(!is.na(dat$type))),
function(d) within(d, type[seq_len(min(nrow(d), counter[1]))] <- type[1])
))
dplyr
library(dplyr)
dat %>%
mutate(grp = cumsum(!is.na(type))) %>%
group_by(grp) %>%
mutate(type = if_else(row_number() <= counter[1], type[1], type)) %>%
ungroup() %>%
select(-grp)
数据
dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text='
orgid date type counter
12345 1-1-17 sale 3
12345 1-2-17 NA NA
12345 1-3-17 NA NA
78945 1-1-17 NA NA
78945 1-2-17 free 2
78945 1-3-17 NA NA')
我有这样的数据,按 'orgid':
分组orgid date type counter
12345 1-1-17 sale 3
12345 1-2-17 NA NA
12345 1-3-17 NA NA
78945 1-1-17 NA NA
78945 1-2-17 free 2
78945 1-3-17 NA NA
对于每个 'orgid',我想 "drag down" 'type' N-1 行,其中 N 由 'counter' 列定义。结果应如下所示:
orgid date type counter
12345 1-1-17 sale 3
12345 1-2-17 sale NA
12345 1-3-17 sale NA
78945 1-1-17 NA NA
78945 1-2-17 free 2
78945 1-3-17 free NA
我相信我可以使用zoo
包中的na.locf
,但我一直无法破解密码。有什么想法吗?
我不认为你可以为此使用 (感谢 Henrik 让我直截了当!)zoo::na.locf
,我不认为它是一个限制因素。
两个解决方案,我相信 data.table
大师可以添加相关的第三个:
基础 R
do.call("rbind.data.frame",
lapply(split(dat, cumsum(!is.na(dat$type))),
function(d) within(d, type[seq_len(min(nrow(d), counter[1]))] <- type[1])
))
dplyr
library(dplyr)
dat %>%
mutate(grp = cumsum(!is.na(type))) %>%
group_by(grp) %>%
mutate(type = if_else(row_number() <= counter[1], type[1], type)) %>%
ungroup() %>%
select(-grp)
数据
dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text='
orgid date type counter
12345 1-1-17 sale 3
12345 1-2-17 NA NA
12345 1-3-17 NA NA
78945 1-1-17 NA NA
78945 1-2-17 free 2
78945 1-3-17 NA NA')