r - R 长到宽,计数和求和
问题描述
我有一个数据如下:
#dt
Method ID Source Amt
A 1 X 10
A 1 Y 20
C 1 Z 30
B 2 Y 15
D 2 Z 10
C 3 X 20
D 3 X 20
E 4 Z 10
E 4 Z 10
我想要的是:
ID Total_Amt Method_A Method_B Method_C Method_D Method_E Source_X Source_Y Source_Z
1 60 2 0 1 0 0 1 1 1
2 25 0 1 0 1 0 0 1 1
3 40 0 0 1 1 0 2 0 0
4 20 0 0 0 0 2 0 0 2
对于Method
和Source
列,我想通过它们来计算计数,ID
并使用它来转换为宽格式,并将列dcast
加起来。Amt
ID
有什么帮助吗?
解决方案
这是使用dplyr
和tidyr
库的一种方式。我们首先计算每个sum
的Amt
值ID
,以长格式获取数据,count
行数并以宽格式返回。
library(dplyr)
library(tidyr)
df %>%
group_by(ID) %>%
mutate(Amt = sum(Amt)) %>%
pivot_longer(cols = c(Method, Source)) %>%
count(ID, value, Amt, name) %>%
pivot_wider(names_from = c(name, value), values_from = n, values_fill = 0)
# ID Amt Method_A Method_C Source_X Source_Y Source_Z Method_B Method_D Method_E
# <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#1 1 60 2 1 1 1 1 0 0 0
#2 2 25 0 0 0 1 1 1 1 0
#3 3 40 0 1 2 0 0 0 1 0
#4 4 20 0 0 0 0 2 0 0 2
推荐阅读
- http-status-code-404 - 为什么我在 MERN 堆栈中出现 Not Found 错误
- python - 如何在 python 中写入文本文件时优化矩阵中的双循环?
- gcloud - Gcloud 错误 401:请求具有无效的身份验证凭据
- javascript - For Loop 上的 Click() 仅适用于第一个按钮
- wordpress - 我的 WordPress 中没有“我的网站”按钮
- postgresql - 在 psql 中,如何使用 CTE 为 Select 查询运行循环并获得只读数据库中显示的输出?
- python - 使用 selenium 无限滚动时摆脱弹出窗口
- c# - 展开时 WinForms TreeView 故障
- asp.net-core - 如何在 Visual Studio 2019 16.8.3 Build 中禁用 ASP.NET Core API 3.1 项目的 SSL?
- qemu - libvirt:在 NUMA 系统上使用大页面