on-internet
← Community

dplyr::first() to choose first non NA value

Stack Overflow ·

I am looking for a way to extract the first and last non-NA value from each group. I am using dplyr::first() and dplyr::last(), but I can´t work out how to choose the first or last non-NA value. library(dplyr) set.seed(123) d <- data.frame( group = rep(1:3, each = 3), year = rep(seq(2000,2002,1),3), value = sample(1:9, r = T)) #Introduce NA values in first row of group 2 and last row of group 3 d %>% mutate( value = case_when( group == 2 & year ==2000 ~ NA_integer_, group == 3 & year ==2002 ~ NA_integer_, TRUE ~ value))%>% group_by(group) %>% mutate( first = dplyr::first(value), last = dplyr::

Comments

Sign in or sign up to comment and upvote.

No comments yet.