This is a similar question to reordering groups with dataframe, however differs in that there are more than two variables. Example data:
raw <- "Date Response ZNumber Latency ZPV
2016-05-04 1 1 445.562 59.666
2016-05-04 2 1 433.890 97.285
2016-05-04 3 1 372.073 53.994
2016-05-04 4 1 282.337 89.686
2016-05-04 4 2 333.186 57.471
2016-05-04 5 1 320.500 71.968
2016-05-04 5 2 280.818 49.187
2016-07-14 1 1 411.849 65.539
2016-07-14 2 1 346.814 50.626"
data <- read.table(text=raw, header = TRUE)
Individual 'Date-Response-ZNumber' and 'Latency-ZPV' is always correctly associated. The ZNumber order per Date-Response should be defined by ascending order of Latency.
The problem in my data is that sometimes when a Date-Response has more than one ZNumber, the Latency order sometimes does not match the ZNumber order e.g. Date=2016-05-04, Response=4 has ascending order in both ZNumber and Latency whereas Date=2016-05-04, Response=5 the ZNumber is ascending while Latency is descending.
I cannot discover the correct split-apply-combine operations.
Output
What I would like performed is both ZNumber and Latency to ascend together within a 'Date-Response' group e.g. Date=2016-05-04, Response=5
"Date Response ZNumber Latency ZPV
2016-05-04 1 1 445.562 59.666
2016-05-04 2 1 433.890 97.285
2016-05-04 3 1 372.073 53.994
2016-05-04 4 1 282.337 89.686
2016-05-04 4 2 333.186 57.471
2016-05-04 5 1 280.818 49.187
2016-05-04 5 2 320.500 71.968
2016-07-14 1 1 411.849 65.539
2016-07-14 2 1 346.814 50.626"
dplyr
Numerous attempts to solve, such as below, have not worked...
library(dplyr)
data <- data %>%
group_by(Date, Response) %>%
arrange(Latency, ZNumber) %>%
arrange(Date, Response)
or, as suggested in the above linked question...
data <- data %>%
arrange(df, group, desc(value))
with the various 'mutating joins' without success. e.g.
data <- data %>%
group_by(Date,Response) %>%
select(Latency) %>%
arrange(Latency) %>%
arrange(Response) %>%
full_join(data,by=c("Date","Response"))
however now has two Latency columns.
sessionInfo()
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
other attached packages:
[1] dplyr_0.5.0
loaded via a namespace (and not attached):
[1] lazyeval_0.2.0 magrittr_1.5 R6_2.2.0 assertthat_0.1 DBI_0.5-1
[6] tools_3.3.2 tibble_1.2 Rcpp_0.12.8