Home > Software design >  Filter or remove first row based on ifelse statement for repeated values
Filter or remove first row based on ifelse statement for repeated values

Time:10-16

I have a df:

ID Age Measurement
1 1 23.5
1 2 24.5
1 3 25.0
2 0 10.0
2 0 11.5
2 1 23.5
2 2 25.5
3 0 9.5
3 1 20.0
4 0 10.5
4 0 11.0
4 1 23.5
4 2 26.5
4 3 27.5

All I want to do if filter out that first measurement for repeated measurements if the age is 0.

df %>%
ifelse(Age == 0, lead(Age) == 0, slice(-1), *Do nothing*)

I just do not know how to get around this^

CodePudding user response:

library(tidyverse)

df %>%
   group_by(ID, Age) %>%
   slice_tail(n = 1) %>%
   ungroup()

CodePudding user response:

Using Dan's code (thank you!):

df2<- RC_data %>%
  filter(is.na(Age))

df<- df%>%
  filter(!(is.na(Age))) %>% 
  group_by(ID, Age) %>%
  slice_tail(n = 1) %>%
  ungroup()

df<- full_join(df, df2)

  • Related