[英]Calculate number of days between specific date and today r
数据:
DB <- data.frame(orderID = c(1,2,3,4,5,6,7,8,9,10),
orderDate = c("1.1.14","16.3.14","11.5.14","21.6.14","29.7.14",
"2.8.14","21.9.14","4.10.14","30.11.14","2.1.15"),
itemID = c(2,3,2,5,12,4,2,3,1,5),
price = c(29.90, 39.90, 29.90, 19.90, 49.90, 9.90, 29.90, 39.90,
14.90, 19.90),
customerID = c(1, 2, 3, 1, 1, 3, 2, 2, 1, 1),
dateofbirth = c("12.1.67","14.10.82","6.8.87","12.1.67","12.1.67",
"6.8.87","14.10.82","14.10.82","12.1.67","12.1.67")
预期的结果[希望我算正确的天数]:
1.daystilllastorder(here 18.02.2015) = c("47", "137", "200", "47",
"47", "200", "137", "137", "47", "47")
2.daysbetweenthelastorders = c("33", "13","83","33", "33", "83", "13", "13", "33", "33",)
嗨,大家好,
不幸的是,我有3个我无法单独解决的新问题-因此,如果您再次偷看我,我将非常高兴:)在数据集中,每个订单都有自己的ID,每个注册用户都有其唯一的customerID。 每个客户都可以订购具有特定价格的商品(带有商品ID)。 用户将他/她的出生日期写在数据库中(如您在上面的:D所示)我想要1.计算从(每个客户的)最后一次订单到今天的天数。 2.计算实际(最新)和2.最新订单之间的天数。3.总计订单之间的天数
已经像这样尝试过了,但是不起作用:
setDT(DB)[, orderDate := as.Date(orderDate, format = "%Y-%m-%d")]
DB[, daystilllastorder := sum(seq[max(orderDate),Sys.Date(), by = customerID]
DB$orderDate <- as.factor(DB$orderDate)
希望您能告诉我什么地方出了问题或告诉我解决此问题的另一种可能性。...
干杯和THX!
这是一个可能的解决方案(我不知道我是否正确理解了3点,但似乎您想要订单之间的平均差?)
首先,我们将orderDate
转换为实际的日期类,然后一切简单
setDT(DB)[, orderDate := as.Date(orderDate, "%d.%m.%y")]
DB[, `:=`(
daystillastord = Sys.Date() - max(orderDate),
daysbetlastord = if(.N == 1L) "first order" else as.character(max(orderDate) - max(orderDate[orderDate != max(orderDate)])),
meandiff = mean(diff(orderDate)),
OrdsLastFullYear = sum(year(orderDate) == year(Sys.Date()) - 1)
),
by = customerID][]
# orderID orderDate itemID price customerID dateofbirth daystillastord daysbetlastord meandiff OrdsLastFullYear
# 1: 1 2014-01-01 2 29.9 1 12.1.67 52 days 33 91.5 4
# 2: 2 2014-03-16 3 39.9 2 14.10.82 142 days 13 101.0 3
# 3: 3 2014-05-11 2 29.9 3 6.8.87 205 days 83 83.0 2
# 4: 4 2014-06-21 5 19.9 1 12.1.67 52 days 33 91.5 4
# 5: 5 2014-07-29 12 49.9 1 12.1.67 52 days 33 91.5 4
# 6: 6 2014-08-02 4 9.9 3 6.8.87 205 days 83 83.0 2
# 7: 7 2014-09-21 2 29.9 2 14.10.82 142 days 13 101.0 3
# 8: 8 2014-10-04 3 39.9 2 14.10.82 142 days 13 101.0 3
# 9: 9 2014-11-30 1 14.9 1 12.1.67 52 days 33 91.5 4
# 10: 10 2015-01-02 5 19.9 1 12.1.67 52 days 33 91.5 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.