Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr group_by() and slice() within group

Tags:

dataframe

r

dplyr

Suppose you have a tibble:

library(tidyverse)

x <- tibble(
   name   = c("alice", "bob", "mary", "mary", "alice", "alice"),
   colour = c(NA, "green", "orange", "orange", NA, NA)
 ) %>% 
 group_by(name)



# A tibble: 6 x 2
# Groups:   name [3]
  name  colour
  <chr> <chr> 
1 alice NA    
2 bob   green 
3 mary  orange
4 mary  orange
5 alice NA    
6 alice NA  

How can you group by name and only return 1 name if all colours within a group are NA?

Expected output:

# A tibble: 4 x 2
  name  colour
  <chr> <chr> 
1 alice NA    
2 bob   green 
3 mary  orange
4 mary  orange
like image 654
Simon Avatar asked Sep 20 '25 20:09

Simon


1 Answers

You can use all inside filter to check if all colours are NA

x %>%
   filter(!(all(is.na(colour)) & 1:n() != 1))
like image 73
Cettt Avatar answered Sep 22 '25 12:09

Cettt