【问题标题】:generate choice switching matrix by group for many groups为许多组按组生成选择切换矩阵
【发布时间】:2016-12-05 11:52:37
【问题描述】:

我想先按计算选择切换概率(下面代码中的user)。然后我将平均组级概率并获得总概率。我有数以万计的组,所以我需要快速的代码。我的代码是 for loop ,运行时间超过 10 分钟。我做了同样的代码/逻辑excel,不到几秒钟。

针对特定用户的m to n 选项switching 定义为选择n at period tm 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


【解决方案1】:

我们可以在 splitting by 'user' 之后使用 tableprop.table

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 所说,split 'user' 的'choice' 列更紧凑

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

【讨论】:

  • 基本上和我在 cmets 中同时发布的一样 :) +1
  • @nicola 抱歉,我在发布此内容时没有看到您的评论。可能页面没有更新,我正忙着发布这个。
  • 别担心,你不能。我们同时做到了。您可以只拆分dt$choice 而不是整个data.frame 以提高效率(拆分更轻,在lapply 中您没有$ 子集操作)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-28
  • 1970-01-01
  • 2020-04-20
  • 2019-12-12
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
相关资源
最近更新 更多