I need help with the following problem. I want to be able to create the column called "desired" in this demo data frame using only the information in columns "bb", "cc", and "dd". The idea is pretty simple: to reverse the order of one variable within group_by groups having filtered or conditioned on one of the columns. My closest attempt so far is shown below but the 'sort' function ignores the groups and sorts across the whole variable.
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
my.df <- data.frame(aa=factor(c(1:24)),
bb=factor(rep(c(1:6), each=4)),
cc=factor(rep(c(1,2), each=4, times=3)),
dd=c(11:14, 21:24, 31:34, 41:44, 51:54, 61:64),
desired=c(11:14, 24:21, 31:34, 44:41, 51:54, 64:61))
my.df %>%
group_by(bb) %>%
mutate(ee=ifelse(cc==2, sort(.$dd, decreasing = TRUE), dd))
#> # A tibble: 24 x 6
#> # Groups: bb [6]
#> aa bb cc dd desired ee
#> <fct> <fct> <fct> <int> <int> <int>
#> 1 1 1 1 11 11 11
#> 2 2 1 1 12 12 12
#> 3 3 1 1 13 13 13
#> 4 4 1 1 14 14 14
#> 5 5 2 2 21 24 64
#> 6 6 2 2 22 23 63
#> 7 7 2 2 23 22 62
#> 8 8 2 2 24 21 61
#> 9 9 3 1 31 31 31
#> 10 10 3 1 32 32 32
#> # ... with 14 more rows
Created on 2018-12-31 by the reprex package (v0.2.1)
Thanks for any help.