Anubhav Dikshit
Anubhav Dikshit

Reputation: 1829

Multiple functions in aggregate

Is is possible that from the following data frame df1

 Branch Loan_Amount TAT
      A         100 2.0
      A         120 4.0
      A         300 9.0
      B         150 1.5
      B         200 2.0

I can use aggregate function to get the following output as a dataframe df2

 Branch Number_of_loans Loan_Amount Total_TAT
      A               3         520      15.0
      B               2         350       3.5

I know I can use nrow to calculate the number_of_loans and merge, but I am looking for a better method.

Upvotes: 4

Views: 6357

Answers (6)

Øyvind Langsrud
Øyvind Langsrud

Reputation: 181

The function aggregate_multiple_fun in the SSBtools package is a wrapper to aggregate that allows multiple functions and functions of several variables. In this case a possibility is

library(SSBtools)
aggregate_multiple_fun(df, by = df["Branch"], 
            vars = c(sum = "Loan_Amount", sum = "TAT", length = "TAT"))

Output:

  Branch Loan_Amount_sum TAT_sum TAT_length
1      A             520    15.0          3
2      B             350     3.5          2

In addition, there are several ways to specify output variable names, directly or via function names. Note that aggregate is called only once.

Upvotes: 0

sashahafner
sashahafner

Reputation: 454

This is an old post but on a common operation, and there should be an easier solution, in my opinion.

Here is a single line alternative that might be simpler.

> aggregate2(df, x = c('Loan_Amount', 'TAT'), by = 'Branch', 
             FUN = list(total = sum, number = length))

  Branch Loan_Amount.total TAT.total Loan_Amount.number TAT.number
1      A               520      15.0                  3          3
2      B               350       3.5                  2          2

aggregate2() is a function in the jumbled repo that I just built on top of the base function aggregate. It calls aggregate once for each FUN function with a bit of work before and after.

Unlike aggregate it accepts multiple functions. Unlike the dplyr solution, it will apply all these functions to all the x variables without e.g., one Loan_Amount = sum(Loan_Amount), for each one.

Upvotes: 2

Oleg Melnikov
Oleg Melnikov

Reputation: 3298

This is hacky and inefficient, but it works and is interesting (it uses aggregate()):

d <- read.table(text="Branch Loan_Amount TAT
A         100 2.0
A         120 4.0
A         300 9.0
B         150 1.5
B         200 2.0",head=TRUE)

library(stringr)
df = aggregate(.~Branch, data=d, FUN=function(x) paste0(length(x), '|',sum(x)))
df_ = cbind(str_split_fixed(df$Loan_Amount, '|', 4)[,c(2,4)], str_split_fixed(df$TAT, '|', 4)[,4])
df_ = apply(df_, 2, as.numeric)
colnames(df_) = c('Number_of_loans','Loan_Amount','Total_TAT')
cbind(df[,'Branch',drop=F], df_)

Producing the desired data.frame:

  Branch Number_of_loans Loan_Amount Total_TAT
1      A               3         520      15.0
2      B               2         350       3.5

Upvotes: 0

jlhoward
jlhoward

Reputation: 59335

Using data.table

library(data.table)
setDT(df)[,list(Number_of_loans=.N, 
                Loan_Amount    =sum(Loan_Amount), 
                Total_TAT      =sum(TAT)), by=Branch]
#    Branch Number_of_loans Loan_Amount Total_TAT
# 1:      A               3         520      15.0
# 2:      B               2         350       3.5

Upvotes: 4

mpalanco
mpalanco

Reputation: 13570

Base package:

df1 <- aggregate(.~ Branch, df, FUN = "sum")
df2 <- setNames(aggregate(Loan_Amount~Branch, df, length)[2], c("Number_of_loans"))
cbind(df1, df2)

Output

  Branch Loan_Amount  TAT Number_of_loans
1      A         520 15.0               3
2      B         350  3.5               2

Package sqldf:

library(sqldf)
sqldf("SELECT Branch, COUNT(Loan_Amount) Number_of_loans, SUM(Loan_Amount) Loan_Amount, SUM(TAT) TAT 
      FROM df 
      GROUP BY Branch")

Output

  Branch Number_of_loans Loan_Amount  TAT
1      A               3         520 15.0
2      B               2         350  3.5

Data

df <- structure(list(Branch = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("A", 
"B"), class = "factor"), Loan_Amount = c(100L, 120L, 300L, 150L, 
200L), TAT = c(2, 4, 9, 1.5, 2)), .Names = c("Branch", "Loan_Amount", 
"TAT"), class = "data.frame", row.names = c(NA, -5L))

Upvotes: 5

scoa
scoa

Reputation: 19867

With dplyr, you could do this:

library(dplyr)
group_by(d,Branch) %>% 
  summarize(Number_of_loans = n(),
            Loan_Amount = sum(Loan_Amount),
            TAT = sum(TAT))

output

Source: local data frame [2 x 4]

  Branch Number_of_loans Loan_Amount   TAT
  (fctr)           (int)       (int) (dbl)
1      A               3         520  15.0
2      B               2         350   3.5

data

d <- read.table(text="Branch Loan_Amount TAT
A         100 2.0
A         120 4.0
A         300 9.0
B         150 1.5
B         200 2.0",head=TRUE)

Upvotes: 4

Related Questions