I would like to reorder the position of NA's in a column, within each level of another categorical variable. For example with this data frame:
df <- data.frame(fact=c(1,1,1,2,2,2), id=rep(1:6), value=c(NA,44,23,NA,NA,76))
I would like to mutate a new column like:
df$newvar <= c(44,23,NA,76,NA,NA)
I would have thought the following would work, but it doesn't:
dfb <- df %>% group_by(fact) %>% mutate(newvar = df$value[order(is.na(df$value))])
Any ideas on how I can do this?
You should remove the df$
part in your mutate statement, otherwise you are referring to the full column, instead of the column per group. So this should work fine:
df %>% group_by(fact) %>% mutate(newvar = value[order(is.na(value))])
Output:
# A tibble: 6 x 4
# Groups: fact [2]
fact id value newvar
<dbl> <int> <dbl> <dbl>
1 1.00 1 NA 44.0
2 1.00 2 44.0 23.0
3 1.00 3 23.0 NA
4 2.00 4 NA 76.0
5 2.00 5 NA NA
6 2.00 6 76.0 NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With