求和时从长到宽重塑 [英] Reshape from long to wide while summing

查看:32
本文介绍了求和时从长到宽重塑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例数据

rankP amount defaulted
   1  45925         1
   1 369550         1
   1 177975         1
   1 157850         0
   2  30400         1
   2  93950         0
   2 194075         1
   3  30975         0
   3  66775         1
   3 225850         1

并且我想转换数据,以便获得每个等级、每个默认状态 (0/1) 的数量.所需的输出如下所示:

and I would like to transform the data so that I'll have the amount per-rank, per-defaulted status (0/1). The required output would look like this:

rankP   0         1
1     157850    593450
2      93950    224475
3      30975    292625

我觉得我遗漏了一些非常简单的东西,到目前为止我没有设法使用 table()aggregate()

I'm feeling like I'm missing something very simple, and so far I didn't manage to do it using either table() or aggregate()

实现这一目标的方法是什么?

What's the way to achieve that?

推荐答案

使用 dplyrtidyr

library(dplyr)
library(tidyr)

df %>% 
  group_by(rankP, defaulted) %>% 
  summarize(amount = sum(amount)) %>% 
  spread(defaulted, amount)

#Source: local data table [3 x 3]
#Groups:

#  rankP      0      1
#1     1 157850 593450
#2     2  93950 224475
#3     3  30975 292625

正如@akrun 提到的,简单地使用 xtabs

As @akrun mentioned, using xtabs simply

xtabs(amount~rankP+defaulted, df)

这篇关于求和时从长到宽重塑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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