Reputation: 625
I'm writing a print method for a package that I'm working on. It's basic task is to display a set of tasks grouped by date. Because working on a console implies that the last thing printed is closest to the prompt, I want the oldest date to be listed last. Without all the hassle of the print method and dispatching, the core code is something along this:
d <- data.frame(thr = as.Date(Sys.time()) + seq(-3,3,1),
tsk = paste0('t', 1:7), stringsAsFactors = FALSE)
d %>% group_by(thr) %>%
do(x = {
thr <- format(.$thr, '%d-%m-%Y')
cat(thr, '\n', .$tsk, '\n')
})
This generates
02-09-2015
t1
03-09-2015
t2
04-09-2015
t3
05-09-2015
t4
06-09-2015
t5
07-09-2015
t6
08-09-2015
t7
But I'd like to order it in reverse chronological order so that the oldest date is printed last:
08-09-2015
t7
07-09-2015
t6
...
In normal (non printing code) this would be easy using arrange(-thr) but I haven't figured out a way to do this in the print function.
Upvotes: 1
Views: 2190
Reputation: 4024
Answer with NA's moved to the top.
library(dplyr)
library(magrittr)
options(stringsAsFactors = FALSE)
data.frame(thr =
as.Date(Sys.time()) + c(seq(-3,3,1), seq(-3,3,1)) %>%
c(NA),
tsk = paste0('t', 1:15)) %>%
arrange(tsk) %>%
group_by(thr) %>%
summarize(
tsk_out =
paste(
thr %>% first %>% format('%d-%m-%Y'),
'\n',
tsk %>% unique %>% paste(collapse = " "),
'\n') ) %>%
arrange(thr %>% order(na.last = FALSE, decreasing = TRUE)) %>%
use_series(tsk_out) %>%
cat
Upvotes: 1
Reputation: 4024
library(dplyr)
library(magrittr)
data.frame(thr = as.Date(Sys.time()) + c(seq(-3,3,1), seq(-3,3,1)),
tsk = paste0('t', c(1:14)), stringsAsFactors = FALSE) %>%
arrange(tsk) %>%
group_by(thr) %>%
summarize(
tsk_out =
paste(
thr %>% first %>% format('%d-%m-%Y'),
'\n',
tsk %>% unique %>% paste(collapse = " "),
'\n') ) %>%
arrange(desc(thr)) %>%
use_series(tsk_out) %>%
cat
Upvotes: 3