r - 将汇总数据帧从长转换为宽(不使用 reshape、reshape2、tydr)
问题描述
简介:我在一个无法安装更多软件包的严格环境中工作。我可以从 {stats} 访问 dcast()、xtabs()、reshape()。我无权访问 tydr、reshape 或 reshape2 包。
现在问题来了:我有一个包含 4 列名称 cust_id、merchant_group、sum 和 max 的汇总数据框,如下所示:
cust_id merchant_group sum max
<int> <chr> <dbl> <dbl>
1 495 AIRLINE 45493 4950
2 495 AUTO RENTAL 3104 1000
3 495 CLOTHING STORES 20928 3140
4 495 DEPARTMENT STORES 1082 495
5 495 DRUG STORES 482 165
我想将它重塑成宽大的形式,如下所示:
cust_id AIRLINE AUTO RENTAL CLOTHING STORES DEPARTMENT STORES DRUG STORES
495 45493 3104 20928 1082 482
495 4950 1000 3140 495 165
我尝试过以下功能:
xtabs(sum~cust_id+merchant_group, data=my.data)
reshape(my.data, idvar = "cust_id", timevar = "merchant_group", direction = "wide")
但不能解决我的问题。提前感谢您的宝贵时间。
解决方案
如果你必须使用stats::reshape()
,你可以
(1) 将数据重塑为更长的格式,其中sum
和max
都在一个列中:
my.data.longer <- stats::reshape(data = my.data,
idvar = 1:2,
v.names = "value",
timevar = "variable",
times = c("sum", "max"),
varying = 3:4,
direction = "long")
看起来像这样(现在不要担心 row.names):
cust_id merchant_group variable value
495.AIRLINE.sum 495 AIRLINE sum 45493
495.AUTO RENTAL.sum 495 AUTO RENTAL sum 3104
495.CLOTHING STORES.sum 495 CLOTHING STORES sum 20928
495.DEPARTMENT STORES.sum 495 DEPARTMENT STORES sum 1082
495.DRUG STORES.sum 495 DRUG STORES sum 482
495.AIRLINE.max 495 AIRLINE max 4950
495.AUTO RENTAL.max 495 AUTO RENTAL max 1000
495.CLOTHING STORES.max 495 CLOTHING STORES max 3140
495.DEPARTMENT STORES.max 495 DEPARTMENT STORES max 495
495.DRUG STORES.max 495 DRUG STORES max 165
(2)将较长的数据重塑为您需要的宽格式:
my.data.wide <- stats::reshape(data = my.data.longer,
idvar = c("cust_id", "variable"),
timevar = "merchant_group",
times = as.character(my.data$merchant_group),
v.names = "value",
direction = "wide")
看起来像这样:
cust_id variable value.AIRLINE value.AUTO RENTAL value.CLOTHING STORES value.DEPARTMENT STORES value.DRUG STORES
495.AIRLINE.sum 495 sum 45493 3104 20928 1082 482
495.AIRLINE.max 495 max 4950 1000 3140 495 165
(3)删除variable
列,更改列names
并重置row.names
:
my.data.wide$variable <- NULL
names(my.data.wide)[2:ncol(my.data.wide)] <- as.character(my.data$merchant_group)
row.names(my.data.wide) <- NULL
my.data.wide
结果是:
cust_id AIRLINE AUTO RENTAL CLOTHING STORES DEPARTMENT STORES DRUG STORES
1 495 45493 3104 20928 1082 482
2 495 4950 1000 3140 495 165
推荐阅读
- r - geom_segment - 平行闪避
- woocommerce-rest-api - 在最新的 woocommerce rest api 上使用自定义搜索查询
- xml - 尽管使用条件,XSLT 节点内容仍显示
- mysql - SELECT 行 COUNT 和另一个行值 MYSQL
- python - 如何在python中使用前缀字段更改AFINN字段
- algorithm - 使用反向替换计算算法的复杂度
- blazor - 将 EditFrom 拆分为多个组件
- node.js - 如何在 AWS sdk nodejs 中更改 aws 配置文件
- google-cloud-platform - 在 GCP cloudbuild.yaml 中指定与“名称”不同的“执行函数”
- javascript - JavaScript add 和 removeEventListeners 带参数的回调