R如何在涉及3个变量的情况下创建类似于数据透视表的数据框? [英] R how to create pivot table-like data frame while 3 variables are involved?
问题描述
我在R中具有以下数据框,该数据框为我提供了客户1,2和3的交易记录.每行显示交易的期间类型和花费的金额.
I have the following data frame in R which gives me the customers 1,2, and 3's transactional record. Each row shows the period type that the transaction has been made and the amount of money he spent.
id<-c(1,2,3,1,1,2,3,2,2)
period<-c("calib","valid","valid","calib","valid","valid","calib","calib","valid")
spent<-c(10,3,8,12,5,5,4,3,5)
df<-data.frame(id,period,spent)
现在我需要创建一个新的数据框,该框为我提供了在不同期间"内每个事务的每个"id"的平均花费".我在excel数据透视表中获得的结果表应如下:
now I need to create a new data frame which gives me the average 'spent' of each 'id' per transaction in different 'period's. The resulted table which I got in in excel pivot table should be as follow:
id calib valid
1 11 5
2 3 4.33
3 4 8
我知道应该有一种方法可以在R中完成这项工作,但是由于我是R中的新手,所以我对此并不了解.我想知道是否有人可以帮助我.
I know there should be a way to make this work in R but since I am new in R I'm not aware of it. I wonder if anyone can help me with this.
推荐答案
您可以使用 reshape2 包中的dcast
来做到这一点(我相信还有很多其他方法):>
You can do this using dcast
from the reshape2 package (among numerous other ways, I'm sure):
library(reshape2)
dcast(df,id~period,fun.aggregate = mean)
id calib valid
1 1 11 5.000000
2 2 3 4.333333
3 3 4 8.000000
(请注意,我假设您打算在数据框中包含spent
向量.)
(Note that I'm assuming you intended to include the spent
vector in your data frame.)
这篇关于R如何在涉及3个变量的情况下创建类似于数据透视表的数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!