Home > OS >  How to check if numbers only increase in a group?
How to check if numbers only increase in a group?

Time:09-17

I would like to check the column "state" within in a group (ID) for to see if numbers are only increasing.

Example:

df <-data.frame("ID" = c("A","A","A","B","B","B"),
                "State"=c(1,2,3,1,4,2))
df %>%
  group_by(ID) %>% 
  mutate(Check = ifelse(State > State[row.number()   1], TRUE, FALSE)))

And the Output I was hoping for: Check: A - TRUE B - FALSE (because in this example 1,4,2 the numbers increases but then decrease)

CodePudding user response:

EDIT: Check Yuriy answer to see a more compact solution maybe harder to read if you do not know about diff and all function in the first place


Code

require(tidyverse)

(
  df
  %>% group_by(ID)
  %>% mutate(Diff = State - lag(State))
  %>% filter(! is.na(Diff))
  %>% summarise(Increasing = all(Diff >= 0))
)

Output

# A tibble: 2 x 2
  ID    Increasing
  <chr> <lgl>           
1 A     TRUE            
2 B     FALSE  

Explanation

(
  df
  %>% group_by(ID)
  %>% mutate(Diff = State - lag(State))
)

  ID    State  Diff
  <chr> <dbl> <dbl>
1 A         1    NA
2 A         2     1
3 A         3     1
5 B         1    NA
6 B         4     3
7 B         2    -2

The difference with the upper line is computed in each subgroup

(
  df
  %>% group_by(ID)
  %>% mutate(Diff = State - lag(State))
  %>% filter(! is.na(Diff))
  %>% summarise( all(Diff >= 0))
) 

The NA lines are deleted and then we have to check if a negative number is present.


Data sample

require(tidyverse)

df <- tribble( ~ ID, ~ State,
                "A",       1,
                "A",       2,
                "A",       3,
                "B",       1,
                "B",       4,
                "B",       2
               )

CodePudding user response:

library(tidyverse)
df <-data.frame("ID" = c("A","A","A","B","B","B"),
                "State"=c(1,2,3,1,4,2))

df %>%
  group_by(ID) %>% 
  summarise(Check = all(diff(State) >= 0))
#> # A tibble: 2 x 2
#>   ID    Check
#>   <chr> <lgl>
#> 1 A     TRUE 
#> 2 B     FALSE
df %>%
  group_by(ID) %>% 
  mutate(Check = all(diff(State) >= 0))
#> # A tibble: 6 x 3
#> # Groups:   ID [2]
#>   ID    State Check
#>   <chr> <dbl> <lgl>
#> 1 A         1 TRUE 
#> 2 A         2 TRUE 
#> 3 A         3 TRUE 
#> 4 B         1 FALSE
#> 5 B         4 FALSE
#> 6 B         2 FALSE

Created on 2021-09-13 by the reprex package (v2.0.1)

  • Related