我是R的新手,拥有以下产品用户名及其使用日期数据(截断输出):
Name, Date
Jane, 01-24-2016 10:02:00
Mary, 01-01-2016 12:18:00
Mary, 01-01-2016 13:18:00
Mary, 01-02-2016 13:18:00
Jane, 01-23-2016 10:02:00
我想对Date
之间的差异做一些分析,特别是每个用户的使用天数。我想绘制直方图以确定用户之间是否存在模式。
由于
答案 0 :(得分:2)
尝试此操作,假设您的数据框为df
:
## in case you have different column names
colnames(df) <- c("Name", "Date")
## you might also have Date as factors when reading in data
## the following ensures it is character string
df$Date <- as.character(df$Date)
## convert to Date object
## see ?strptime for various available format
## see ?as.Date for Date object
df$Date <- as.Date(df$Date, format = "%m-%d-%Y %H:%M:%S")
## reorder, so that date are ascending (see Jane)
## this is necessary, otherwise negative number occur after differencing
## see ?order on ordering
df <- df[order(df$Name, df$Date), ]
## take day lags per person
## see ?diff for taking difference
## see ?tapply for applying FUN on grouped data
## as.integer() makes output clean
## if unsure, compare with: lags <- with(df, tapply(Date, Name, FUN = diff))
lags <- with(df, tapply(Date, Name, FUN = function (x) as.integer(diff(x))))
对于你截断的数据(有5行),我得到:
> lags
$Jane
[1] 1
$Mary
[1] 0 1
lags
是一个列表。如果您想获取Jane的信息,请lags$Jane
。要获得直方图,请执行hist(lags$Jane)
。此外,如果您想简单地为所有客户生成直方图,忽略个体差异,请使用hist(unlist(lags))
。 unlist()
将列表折叠为单个向量。
<强>注释:强>
tapply
用于多个索引?也许你可以尝试使用paste
来首先构建辅助索引的技巧; density
和中心极限定理等来快速地使事情复杂化,以实现可视化。所以我删除了我的其他答案。答案 1 :(得分:2)
我们可以将data.table
与lubridate
library(lubridate)
library(data.table)
setDT(df1)[order(mdy_hms(Date)), .(Diff=as.integer(diff(as.Date(mdy_hms(Date))))), Name]
# Name Diff
#1: Mary 0
#2: Mary 1
#3: Jane 1
如果有多个分组变量,即“ID”,我们可以将其放在by
setDT(df1)[order(mdy_hms(Date)), .(Diff=as.integer(diff(as.Date(mdy_hms(Date))))),
by = .(Name, ID)]