多种功能合计 [英] Multiple functions in aggregate

查看:79
本文介绍了多种功能合计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能来自以下数据帧df1

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

我可以使用聚合函数将以下输出作为数据框df2

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

我知道我可以使用nrow来计算number_of_loans并合并,但是我正在寻找更好的方法。

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

推荐答案

使用dplyr,您可以这样做:

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))

输出

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

数据

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)

这篇关于多种功能合计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆