89_Simple
89_Simple

Reputation: 3815

Copy preceding row if condition is met

My data

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

Rows for which I have no data, the id and value columns have no.data and 0. For all rows where I have no data (id == no.data and value == 0), I want to copy the value and id from the preceding row.

    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

Something like:

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 ))      

Upvotes: 2

Views: 265

Answers (2)

akrun
akrun

Reputation: 887991

We could replace the 0s by NA and then do a fill

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

Upvotes: 2

s_baldur
s_baldur

Reputation: 33753

Unless you have a very big dataset a simple loop should do

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")]
  }
}

Upvotes: 1

Related Questions