按位置将值转换为缺失值

Transform value into missing by position

在数据集中,我需要转换为缺少列 value 中的值,在两种情况下:

  1. 如果按类型分组,该行是最后一行
  2. 如果按类型分组,下一个值行是缺失值

这解决了第一部分:

toy %>% 
  group_by(type) %>%
  mutate(value = ifelse(row_number()==max(row_number()),NA,value))

我该如何处理第二个问题?提前致谢

toy <- data_frame(type=c(rep("A",4),rep("B",4)),year=rep(c(1:4),2),value=c(1,1,NA,1,1,1,1,1))

# A tibble: 8 x 3
  type   year value
  <chr> <int> <dbl>
1 A         1     1
2 A         2     1
3 A         3    NA
4 A         4     1
5 B         1     1
6 B         2     1
7 B         3     1
8 B         4     1


expected <- data_frame(type=c(rep("A",4),rep("B",4)),year=rep(c(1:4),2),value=c(1,NA,NA,NA,1,1,1,NA))

  type   year value
  <chr> <int> <dbl>
1 A         1     1
2 A         2    NA
3 A         3    NA
4 A         4    NA
5 B         1     1
6 B         2     1
7 B         3     1
8 B         4    NA

使用 lead 你可以结合这两个条件:

library(dplyr)

toy %>%
  group_by(type) %>%
  mutate(value = replace(value, is.na(lead(value)), NA)) %>%
  ungroup

#  type   year value
#  <chr> <int> <dbl>
#1 A         1     1
#2 A         2    NA
#3 A         3    NA
#4 A         4    NA
#5 B         1     1
#6 B         2     1
#7 B         3     1
#8 B         4    NA

lead 将给出下一个值,如果它是 NA,我们将当前值更改为 NA。此外 lead returns 最后一个值默认为 NA 因此第一个条件 (If grouping by type, the line is the last line) 自动满足。


同样可以用data.table解决:

library(data.table)

setDT(toy)[,value := replace(value, is.na(shift(value, type = 'lead')),NA), type]