gpt4 book ai didi

r - 数据框子集内的计算 [R]

转载 作者:行者123 更新时间:2023-12-02 05:26:52 26 4
gpt4 key购买 nike

在子集计算方面遇到困难。我能够使用 avetapplyddply 获得客户平均购买量(因素)等总体统计数据,但我无法计算 <每个客户的 strong>逐次访问 统计数据。下面一些简化的数据来说明我的数据和理想的结果。

当前数据框:(请注意,访问 #1 是最近的访问)

  customer  visit      date    purchase_amt
sarah 2 2013-08-09 5
sarah 3 2013-07-21 8
sarah 4 2013-06-23 9
sarah 5 2013-06-02 1
sarah 1 2013-08-20 8
henry 1 2013-07-04 4
che 1 2013-08-27 2
che 2 2013-07-27 1
che 3 2013-07-05 8
che 4 2013-06-14 3
dt 3 2013-04-05 9
dt 2 2013-06-07 1
dt 1 2013-07-11 6

这些是我正在寻找的结果:

customer  visit    date purchase_amt    days since  amt_diff
sarah 2 2013-08-09 5 19 -3
sarah 3 2013-07-21 8 28 -1
sarah 4 2013-06-23 9 21 8
sarah 5 2013-06-02 1 NA NA
sarah 1 2013-08-20 8 11 3
henry 1 2013-07-04 4 NA NA
che 1 2013-08-27 2 31 1
che 2 2013-07-27 1 22 -7
che 3 2013-07-05 8 21 5
che 4 2013-06-14 3 NA NA
dt 3 2013-04-05 9 NA NA
dt 2 2013-06-07 1 63 -8
dt 1 2013-07-11 6 34 5

总而言之,我想找到客户的最近访问及其属性,然后找到下一次访问属性并计算两者的各种统计数据。当没有更多以前的访问时返回“NA”。

最佳答案

是这样的吗?假设您的数据名为 df:

library(plyr)

# convert dates to class 'Date'
df$date <- as.Date(df$date)

# order by customer and date
df <- df[order(df$customer, df$date), ]
# or since plyr is loaded anyway:
df <- arrange(df, customer, date)

# per customer, calculate differences in date and purchase, between consecutive visits
# pad differences with a leading NA
df2 <- ddply(.data = df, .variables = .(customer), mutate,
days_since = c(NA, diff(date)),
amt_diff = c(NA, diff(purchase_amt)))

df2
# customer visit date purchase_amt days_since amt_diff
# 1 che 4 2013-06-14 3 NA NA
# 2 che 3 2013-07-05 8 21 5
# 3 che 2 2013-07-27 1 22 -7
# 4 che 1 2013-08-27 2 31 1
# 5 dt 3 2013-04-05 9 NA NA
# 6 dt 2 2013-06-07 1 63 -8
# 7 dt 1 2013-07-11 6 34 5
# 8 henry 1 2013-07-04 4 NA NA
# 9 sarah 5 2013-06-02 1 NA NA
# 10 sarah 4 2013-06-23 9 21 8
# 11 sarah 3 2013-07-21 8 28 -1
# 12 sarah 2 2013-08-09 5 19 -3
# 13 sarah 1 2013-08-20 8 11 3

关于r - 数据框子集内的计算 [R],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18944859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com