为了账号安全,请及时绑定邮箱和手机立即绑定

一次重塑多个值

一次重塑多个值

交互式爱情 2019-09-24 16:47:21
我有一个很长的数据集,我想扩大范围,我很好奇是否有一种方法可以使用R中的reshape2或tidyr包一步完成所有这些工作。数据框df如下所示:id  type    transactions    amount20  income       20          10020  expense      25          9530  income       50          30030  expense      45          250我想得到这个:id  income_transactions expense_transactions    income_amount   expense_amount20       20                           25                 100             9530       50                           45                 300             250我知道我可以通过例如reshape2来实现这一目标:dcast(df, id ~  type, value.var="transactions")但是,是否有一种方法可以一次处理“交易”和“金额”变量,从而一次重塑整个df?理想情况下,使用新的更合适的列名?
查看完整描述

2 回答

?
开心每一天1111

TA贡献1836条经验 获得超12个赞

在“ reshape2”中,您可以使用recast(尽管根据我的经验,这不是众所周知的功能)。


library(reshape2)

recast(mydf, id ~ variable + type, id.var = c("id", "type"))

#   id transactions_expense transactions_income amount_expense amount_income

# 1 20                   25                  20             95           100

# 2 30                   45                  50            250           300

您还可以使用基数R reshape:


reshape(mydf, direction = "wide", idvar = "id", timevar = "type")

#   id transactions.income amount.income transactions.expense amount.expense

# 1 20                  20           100                   25             95

# 3 30                  50           300                   45            250

或者,你可以melt和dcast,像这样的(这里“data.table”):


library(data.table)

library(reshape2)

dcast.data.table(melt(as.data.table(mydf), id.vars = c("id", "type")), 

                 id ~ variable + type, value.var = "value")

#    id transactions_expense transactions_income amount_expense amount_income

# 1: 20                   25                  20             95           100

# 2: 30                   45                  50            250           300

在dcast.data.table“ data.table”(1.9.8)的更高版本中,您将可以直接执行此操作。如果我正确理解的话,@ Arun尝试实现的内容将是在无需首先melt获取数据的情况下进行重塑,这就是当前发生的情况recast,本质上是melt+ dcast操作序列的包装。


而且,为彻底起见,这里是tidyr方法:


library(dplyr)

library(tidyr)

mydf %>% 

  gather(var, val, transactions:amount) %>% 

  unite(var2, type, var) %>% 

  spread(var2, val)

#   id expense_amount expense_transactions income_amount income_transactions

# 1 20             95                   25           100                  20

# 2 30            250                   45           300                  50


查看完整回答
反对 回复 2019-09-24
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

使用data.table v1.9.6 +,我们可以value.var同时转换多个列(并在中使用多个聚合函数fun.aggregate)。请查看?dcast更多信息以及示例部分。


require(data.table) # v1.9.6+

dcast(dt, id ~ type, value.var=names(dt)[3:4])

#    id transactions_expense transactions_income amount_expense amount_income

# 1: 20                   25                  20             95           100

# 2: 30                   45                  50            250           300


查看完整回答
反对 回复 2019-09-24
  • 2 回答
  • 0 关注
  • 505 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信