【发布时间】:2025-11-24 09:40:01
【问题描述】:
我有一个很长的数据集我想扩大,我很好奇是否有一种方法可以使用 R 中的 reshape2 或 tidyr 包一步完成。
数据框df如下所示:
id type transactions amount
20 income 20 100
20 expense 25 95
30 income 50 300
30 expense 45 250
我想解决这个问题:
id income_transactions expense_transactions income_amount expense_amount
20 20 25 100 95
30 50 45 300 250
我知道我可以通过例如 reshape2 获得其中的一部分:
dcast(df, id ~ type, value.var="transactions")
但是有没有办法一次性重塑整个 df,同时解决“交易”和“金额”变量?最好使用新的更合适的列名?
【问题讨论】:
标签: r dataframe reshape reshape2 tidyr