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