R 上次订单和所有订单的平均成本之和
数据: 嗨, 我有一个问题要为我的老板解决,所以如果你能帮我:) 在数据集中,每个订单都有自己的id,每个注册用户都有自己唯一的customerID。每个客户都可以订购物品(带有ItemID),这些物品有特定的价格。 我想计算订单的价格,但有两个问题: 1.我想要每个客户上一次订单的价值(总和)((总结每个用户上一次订单中所有订购物品的价格[今天的日期是15.10.14]) 2.每个用户[其订单]的平均订单价格R 上次订单和所有订单的平均成本之和,r,R,数据: 嗨, 我有一个问题要为我的老板解决,所以如果你能帮我:) 在数据集中,每个订单都有自己的id,每个注册用户都有自己唯一的customerID。每个客户都可以订购物品(带有ItemID),这些物品有特定的价格。 我想计算订单的价格,但有两个问题: 1.我想要每个客户上一次订单的价值(总和)((总结每个用户上一次订单中所有订购物品的价格[今天的日期是15.10.14]) 2.每个用户[其订单]的平均订单价格 我还想将结果作为新列添加到现有数据集中 我已经试过了: orderValueOfLa
我还想将结果作为新列添加到现有数据集中 我已经试过了:
orderValueOfLastOrder = c(34.80, 39.90, 39.80, 34.80, 34.80, 39.80, 39.90, 39.90, 34.80, 34.80)
AverageValue = c(67.25, 54.85, 39.80, 67.25, 67.25, 39.80, 54.85, 54.85, 67.25, 67.25)
DB1$orderValueOfLastOrder下面是一个使用data.table
包的简单高效的解决方案
DB1$orderValueOfLastOrder<- with(DB1, ave(as.numeric(DB1$orderDate),
price, FUN = function(x) sum(x ==max(x))))
如果你喜欢将其保留为data.frame
格式,只需使用setDF(DB)
(你需要data.table
v1.9.4>=或者DB这看起来……你们是在同一个地方工作吗?是我的兄弟,我们都为同一个老板工作:)明天我会和他谈谈:所以希望他能给出一些反馈:)谢谢你的帮助,大卫!我甚至可以在没有数据帧或数据表的情况下做这件事吗?不确定你的意思我从他回答问题时得到的答案中复制了这部分(我哥哥使用的),使用了(DB1,ave(customerID,customerID,FUN=length))DB2这仍然是一个数据帧
DB1$orderValueOfLastOrder<- with(DB1, ave(as.numeric(DB1$orderDate),
price, FUN = function(x) sum(x ==max(x))))
library(data.table)
setDT(DB)[, orderDate := as.Date(orderDate, format = "%d.%m.%y")]
DB[, `:=` (orderValueOfLastOrder = sum(price[orderDate == max(orderDate)]),
AverageValue = sum(price)/length(unique(orderDate))), by = customerID]
setDF(DB)[]
# orderID orderDate itemID price customerID orderValueOfLastOrder AverageValue
# 1 1 2014-01-01 2 29.9 1 34.8 67.25
# 2 2 2014-01-01 3 39.9 2 39.9 54.85
# 3 3 2014-01-01 2 29.9 3 39.8 39.80
# 4 4 2014-01-01 5 19.9 1 34.8 67.25
# 5 5 2014-01-01 12 49.9 1 34.8 67.25
# 6 6 2014-01-01 4 9.9 3 39.8 39.80
# 7 7 2014-01-01 2 29.9 2 39.9 54.85
# 8 8 2014-01-02 3 39.9 2 39.9 54.85
# 9 9 2014-01-02 1 14.9 1 34.8 67.25
# 10 10 2014-01-02 5 19.9 1 34.8 67.25
class(DB)
## [1] "data.frame"