Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if the previous value is present in the dataset with a logical operation [R]

I have this dataset

structure(list(N = c("a", "b", "a", "b", "c", "a", "c"), S = c("3", 
"3", "2", "2", "2", "1", "1")), class = "data.frame", row.names = c(NA, 
-7L))

And I would like to verify if all group ‘N’ have a previous observation ‘S’. And that with a logical operation

library(tidyverse)
df %>% group_by(N) %>% arrange(desc(S)) %>% mutate(L = ifelse(****))

The output should looks like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

N S P
a 3 TRUE
b 3 TRUE
a 2 TRUE
b 2 FALSE
c 2 TRUE
a 1 FALSE
c 1 FALSE

>Solution :

How about this – it sorts by S within group and then identifies the first (smallest value of S) as FALSE and the others as TRUE.

library(dplyr)
dat <- structure(list(N = c("a", "b", "a", "b", "c", "a", "c"), 
S = c("3", "3", "2", "2", "2", "1", "1")), class = "data.frame", row.names = c(NA,-7L))

dat %>% 
  arrange(S, .by_group = TRUE) %>% 
  group_by(N) %>% 
  mutate(1:n() > 1)
#> # A tibble: 7 × 3
#> # Groups:   N [3]
#>   N     S     `1:n() > 1`
#>   <chr> <chr> <lgl>      
#> 1 a     1     FALSE      
#> 2 c     1     FALSE      
#> 3 a     2     TRUE       
#> 4 b     2     FALSE      
#> 5 c     2     TRUE       
#> 6 a     3     TRUE       
#> 7 b     3     TRUE

Created on 2023-03-09 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading