Home > OS >  Replace value when value above and below are the same
Replace value when value above and below are the same

Time:01-27

I have the following dataframe df (dput below):

> df
   group value
1      A     2
2      A     2
3      A     3
4      A     2
5      A     1
6      A     2
7      A     2
8      A     2
9      B     3
10     B     3
11     B     3
12     B     4
13     B     3
14     B     3
15     B     4
16     B     4

I would like to replace value when the value above and below are the same per group. For example row 3 has a value above of 2 and below of 2 which means the 3 should be 2. The desired output should look like this:

   group value
1      A     2
2      A     2
3      A     2
4      A     2
5      A     2
6      A     2
7      A     2
8      A     2
9      B     3
10     B     3
11     B     3
12     B     3
13     B     3
14     B     3
15     B     4
16     B     4

So I was wondering if anyone knows how to replace values when the value above and below are the same like in the example above?


dput data:

df<-structure(list(group = c("A", "A", "A", "A", "A", "A", "A", "A", 
"B", "B", "B", "B", "B", "B", "B", "B"), value = c(2, 2, 3, 2, 
1, 2, 2, 2, 3, 3, 3, 4, 3, 3, 4, 4)), class = "data.frame", row.names = c(NA, 
-16L))

CodePudding user response:

With ifelse, lead and lag:

library(dplyr)
df %>% 
  mutate(value = ifelse(lead(value, default = TRUE) == lag(value, default = TRUE), 
                        lag(value), value))

   group value
1      A     2
2      A     2
3      A     2
4      A     2
5      A     2
6      A     2
7      A     2
8      A     2
9      B     3
10     B     3
11     B     3
12     B     3
13     B     3
14     B     3
15     B     4
16     B     4
  • Related