我有一个如下所示的数据框列:
a
<int>
1 11127
2 0
3 0
4 NA
5 0
6 0
7 NA
8 0
9 11580
11 0
12 NA
13 0
Run Code Online (Sandbox Code Playgroud)
我想从最后一个非零值开始依次填充 NA 值,以便最终结果如下所示:
a
<int>
1 11127
2 0
3 0
4 11128
5 0
6 0
7 11129
8 0
9 11580
11 0
12 11581
13 0
Run Code Online (Sandbox Code Playgroud)
是否有dplyr(最好)或基本的 R 方式来做到这一点?我宁愿避免 for 循环,因为我的行数非常大。
谢谢。
一种选择:
library(dplyr)
df %>%
group_by(idx = cumsum(!(is.na(a) | a == 0)), is.na(a)) %>%
mutate(rn = row_number()) %>%
group_by(idx) %>%
mutate(a = coalesce(a, first(a) + rn)) %>%
ungroup() %>%
select(a)
Run Code Online (Sandbox Code Playgroud)
输出:
# A tibble: 12 x 1
a
<int>
1 11127
2 0
3 0
4 11128
5 0
6 0
7 11129
8 0
9 11580
10 0
11 11581
12 0
Run Code Online (Sandbox Code Playgroud)
如果速度是一个问题,也许data.table等价物会稍微快一点:
library(data.table)
setDT(df)[, rn := rowid(a), .(cumsum(!(is.na(a) | a == 0)), is.na(a))][
, a := fcoalesce(a, first(a) + rn), by = cumsum(!(is.na(a) | a == 0))][
, rn := NULL]
Run Code Online (Sandbox Code Playgroud)
编辑
IMO 分组然后获取NAs的行索引并不是很优雅;您在其他解决方案中看到的效果要好得多(例如使用cumsum)。
使用fcoalesce,然后可以data.table一步解决问题:
library(data.table)
setDT(df)[, a := fcoalesce(a, first(a) + cumsum(is.na(a))), by = cumsum(!(is.na(a) | a == 0))]
Run Code Online (Sandbox Code Playgroud)
利用的一种解决方案dplyr可能是:
df %>%
group_by(id = cumsum(!is.na(a) & a != 0)) %>%
mutate(a = ifelse(is.na(a), first(a) + cumsum(is.na(a)), a))
a id
<int> <int>
1 11127 1
2 0 1
3 0 1
4 11128 1
5 0 1
6 0 1
7 11129 1
8 0 1
9 11580 2
10 0 2
11 11581 2
12 0 2
Run Code Online (Sandbox Code Playgroud)