我想先按组(下面代码中的user
)计算选择切换概率。然后我将组级概率平均并得到总概率。我有数以万计的组,所以我需要代码快。我的代码是一个 for loop
,运行需要 10 多分钟。我做了同样的代码/逻辑 excel,它只需要不到几秒钟。
特定用户选择m 到n
的切换
被定义为观察的份额,其选择是n at period t
和m 在时间段 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
最佳答案
我们可以使用 table
和 prop.table
after split
by 'user'
lst <- lapply(split(dt, dt$user), function(x)
table(factor(x$choice, levels= 1:3), factor(c(x$choice[-1], NA), levels=1:3)))
如@nicola 所述,按“用户”拆分
“选择”列更紧凑
lst <- lapply(split(dt$choice, dt$user), function(x)
table(factor(x, levels = 1:3), factor(c(x[-1], NA), levels = 1:3)))
lst$C
# 1 2 3
#1 0 1 1
#2 1 0 0
#3 0 0 1
prb <- lapply(lst, prop.table, 1)
prb$C
# 1 2 3
# 1 0.0 0.5 0.5
# 2 1.0 0.0 0.0
# 3 0.0 0.0 1.0
关于r - 为多组按组生成选择切换矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38681245/