I have a large dataframe that I have grouped by Date
. Within each date group, I'd like to keep the rows for rooms that are next door to one another, i.e. Room.num
= any Room.num
in group +/- 1
Date Room.num
1 2019.08.21 1
2 2019.08.21 2
3 2020.07.18 6
4 2020.07.18 1
5 2020.07.18 3
I want to end up with just
Date Room.num
1 2019.08.21 1
2 2019.08.21 2
df %>%
group_by(Date)
filter(Room.num=1)
which gives me
Date Room.num
1 2019.08.21 1
4 2020.07.18 1
df %>%
group_by(Date)
filter(any(Room.num=1))
This gives me
Date Room.num
1 2019.08.21 1
2 2019.08.21 2
3 2020.07.18 6
4 2020.07.18 1
5 2020.07.18 3
i.e. any group with a Room.num=1
Room.num
in that Date
groupdf %>%
group_by(Date)
filter(Room.num==any(Room.num)+1)
I get
Date Room.num
2 2019.08.21 2
The second Room.num
is always = 1
I think you can do this in tidyverse
df <- read.table(header = T, text = 'Date Room.num
1 2019.08.21 1
2 2019.08.21 2
3 2020.07.18 6
4 2020.07.18 1
5 2020.07.18 3
')
library(tidyverse)
df %>%
group_by(Date) %>%
filter(map_lgl(Room.num, ~ .x %in% c(Room.num -1, Room.num +1))) %>%
ungroup()
#> # A tibble: 2 x 2
#> Date Room.num
#> <chr> <int>
#> 1 2019.08.21 1
#> 2 2019.08.21 2
If you, however, want to avoid purrr::map_lgl
use this similar baseR function like this
df %>%
group_by(Date) %>%
filter(unlist(Map(\(.x) .x %in% c(Room.num -1, Room.num +1), Room.num))) %>%
ungroup()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments