I aggregate()
the value
column sums per site
levels of the R data.frame given below:
set.seed(2013)
df <- data.frame(site = sample(c("A","B","C"), 10, replace = TRUE),
currency = sample(c("USD", "EUR", "GBP", "CNY", "CHF"),10, replace=TRUE, prob=c(10,6,5,6,0.5)),
value = sample(seq(1:10)/10,10,replace=FALSE))
df.site.sums <- aggregate(value ~ site, data=df, FUN=sum)
df.site.sums
# site value
#1 A 0.2
#2 B 0.6
#3 C 4.7
However, I would like to be able to specify the row order of the resulting df.site.sums
. For instance like:
reorder <- c("C","B","A")
?special_sort(df, BY=site, ORDER=reorder) # imaginary function
# site value
#1 C 4.7
#2 B 0.6
#3 A 0.2
How can I do this using base R? Just to be clear, this is essentially a data frame row ordering question where the context is the aggregate()
function (which may or may not matter).
This is relevant but does not directly address my issue, or I am missing the crux of the solution.
UPDATE
For future reference, I found a solution to ordering a data.frame's rows with respect to a target vector on this link. I guess it can be applied as a post-processing step.
df.site.sums[match(reorder,df.site.sums$site),]