如果满足条件,则复制前一行

时间:2018-05-16 14:58:38

标签: r dplyr

我的数据

set.seed(123)
df <- data.frame(loc = rep(1:5, each = 5),value = sample(0:4, 25, replace = T))
a <- c("x","y","z","k")
df$id <- ifelse(df$value == 0, "no.data", sample(a,1))
head(df)

   loc value     id
1   1     1       z
2   1     3       z
3   1     2       z
4   1     4       z
5   1     4       z
6   2     0 no.data

我没有数据的行,idvalue列包含no.data0。对于我没有数据(id == no.datavalue == 0)的所有行,我想复制前一行中的valueid

    loc value   id
 1   1     1    z
 2   1     3    z
 3   1     2    z
 4   1     4    z
 5   1     4    z
 6   2     4    z

类似的东西:

df %>% group_by(loc) %>% mutate(value = ifelse(value == 0, copy the value from preceding row), id = ifelse(id== "no.data", copy the id from preceding row ))      

2 个答案:

答案 0 :(得分:2)

我们可以将0s替换为NA,然后执行fill

library(tidyverse)
library(naniar)
df %>% 
   replace_with_na(replace = list(value = 0, id = "no.data")) %>% 
   fill(value, id)

答案 1 :(得分:1)

除非你有一个非常大的数据集,否则应该做一个简单的循环

for (r in 2:nrow(df)) {
  if (with(df[r, ], id == "no.data" && value == 0)) {
    df[r, c("id", "value")] <- df[r - 1L, c("id", "value")]
  }
}