【发布时间】:2016-12-05 11:52:37
【问题描述】:
我想先按组计算选择切换概率(下面代码中的user)。然后我将平均组级概率并获得总概率。我有数以万计的组,所以我需要快速的代码。我的代码是 for loop ,运行时间超过 10 分钟。我做了同样的代码/逻辑excel,不到几秒钟。
针对特定用户的m to n 选项switching 定义为选择n at period t 和m at period t-1 的观察的份额
我的原始代码首先通过 for 循环标记第一次和最后一次购买。然后使用另一个for循环来获取切换矩阵。我只能按整个数据而不是按组创建切换矩阵。即便如此,它仍然非常缓慢。添加用户会使其更慢。
t<-c(1,2,1,1,2,3,4,5)
user<-c('A','A','B' ,'C','C','C','C','C')
choice<-c(1,1,2,1,2,1,3,3)
dt<-data.frame(t,user,choice)
t user choice
1 A 1
2 A 1
1 B 2
1 C 1
2 C 2
3 C 1
4 C 3
5 C 3
# **step one** create a second choice column for later construction of the switching matrix
#Label first purchase and last purchase is zero
for (i in 1:nrow(dt))
{ ifelse (dt$user[i+1]==dt$user[i],dt$newcol[i+1]<-0,dt$newcol[i+1]<-1) }
# **step two** create stitching matrix
# switching.m is a empty matrix with the size of total chocie:3x3 here
length(unique(dt$user))
total.choice<-3
switching.m<-matrix(0,nrow=total.choice,ncol=total.choice)
for (i in 1:total.choice)
{
for(j in 1:total.choice)
{
if(length(nrow(switching.m[switching.m[,1]==i& switching.m[,2]==j,])!=0))
{switching.m[i,j]=nrow(dt[dt[,1]==i&dt[,2]==j,])}
else {switching.m[i,j]<0}
}
}
特定用户/组的期望输出是这样的。即使用户根本没有做出特定选择,输出也应该具有相同的矩阵大小
# take user C
#output for switching matrix
second choice
first 1 2 3
1 0 1 1
2 1 0 0
3 0 0 1
#output for switching probability
second choice
first 1 2 3
1 0 0.5 0.5
2 1 0 0
3 0 0 1
【问题讨论】:
-
@akrun,添加代码
-
由于某种原因,您的代码抛出错误。请检查括号。
-
也许可以试试
lapply(split(dt$choice,dt$user),function(x) table(x[-length(x)],x[-1]))。 -
@akrun 现在代码应该可以工作了。我无法按组制作它。只有整个数据集才能做到
-
尝试拆分 fir 然后 df %>% group_by(user) %>% mutate(Flag = as.integer(row_number()
标签: r dplyr data-manipulation