Home > Blockchain >  How to mutate a cell based on the comparison of a cell in same row to the next cell in a data frame
How to mutate a cell based on the comparison of a cell in same row to the next cell in a data frame

Time:05-06

I'm trying to mutate a cell based on the comparison of a cell in the same row to the next cell in the same column with dplyr. I read some posts but couldn't find something to solve my problem.

As an example, I have this data:

sampleframe <- data.frame("value1" = c(15,18,18,22,19,19,25,20,20),
                          "value2" = c(rep(NA,9)))

enter image description here

What I want is, that the cell in column value2 is overwritten with a 1 if the value of the cell in column value1 and the next cell in column value1 are identical.

Wanted result:

enter image description here

This idea does not work:

df <- sampleframe %>%
      mutate(value2 = case_when(identical(value1, lead(value1)) ~ 1, TRUE ~ as.numeric(value2)))

Any suggestions for syntax that can do this?

CodePudding user response:

You have been almost there ;)

sampleframe %>% 
      mutate(value2= case_when(
        value1 == dplyr::lead(value1) ~ 1, 
        TRUE ~ NA_real_
      ))

      value1 value2
    1     15     NA
    2     18      1
    3     18     NA
    4     22     NA
    5     19      1
    6     19     NA
    7     25     NA
    8     20      1
    9     20     NA

CodePudding user response:

An if_else option using dplyr:

library(dplyr)
sampleframe %>% mutate(value2 = if_else(value1 == lead(value1), 1, NA_real_))

Output:

  value1 value2
1     15     NA
2     18      1
3     18     NA
4     22     NA
5     19      1
6     19     NA
7     25     NA
8     20      1
9     20     NA

An ifelse option using base:

transform(sampleframe, value2 = ifelse(value1 == c(tail(value1, -1), NA), 1, NA))

Output:

  value1 value2
1     15     NA
2     18      1
3     18     NA
4     22     NA
5     19      1
6     19     NA
7     25     NA
8     20      1
9     20     NA
  • Related