我有这些数据:
df <- tibble(a = c(NA, NA, 1, NA, NA, NA, 1, NA, NA))
我想用计数来填充 1 出现后的 NA。像这样:
df2 <- tibble(a = c(NA, NA, 1, 2, 3, 4, 1, 2, 3))
目前我还没有解决办法。有什么想法吗?
最佳答案
在 tidyverse
中解决此问题的一种可能方法:
library(dplyr)
df %>%
# return TRUE or FALSE (1 or 0) if is not NA and run cummulative sum to identify groups
dplyr::mutate(grp = cumsum(!is.na(a))) %>%
# build grouping
dplyr::group_by(grp) %>%
# give rownumber per group if group != 0 (first rows until a = 1 for the frist time
dplyr::transmute(a = ifelse(grp != 0, dplyr::row_number(), NA)) %>%
# release groupings to prevent unwanted behaviour down stream
dplyr::ungroup() %>%
# unselect grp if you do not need it further on in your calculations
dplyr::select(-grp)
# A tibble: 9 x 1
a
<int>
1 NA
2 NA
3 1
4 2
5 3
6 4
7 1
8 2
9 3
关于r - 计算值 1 之后的行,其中其余行在 r 中为 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75687913/