String R-获取给定时间段内最常见的字符串值(模式)

String R-获取给定时间段内最常见的字符串值(模式),string,r,plyr,mode,String,R,Plyr,Mode,我曾希望使用ddply的mode函数按时间段查找某个用户最常见的字符串 这与问题和挑战有很大关系 使用与此类似的数据集: Data <- data.frame( groupname = as.factor(sample(c("red", "green", "blue"), 100, replace = TRUE)), timeblock = sample(1:10, 100, replace = TRUE), someuser = sample(c("bob", "

我曾希望使用ddply的mode函数按时间段查找某个用户最常见的字符串

这与问题和挑战有很大关系

使用与此类似的数据集:

Data <- data.frame(
    groupname = as.factor(sample(c("red", "green", "blue"), 100, replace = TRUE)),
    timeblock = sample(1:10, 100, replace = TRUE),
    someuser = sample(c("bob", "sally", "sue"), 100, replace = TRUE))
  • 如何按时间段按用户查找最常见的组名? 其结果类似于:
  • 如果groupname是按级别组织的,我如何才能获得每个时间段中的最高级别

  • 使用
    plyr中的
    ddply

    ddply(Data, .(timeblock, groupname, someuser),
      function(x){as.character(
                        unique(
                          x$groupname[x$someuser==
                                        names(which.max(table(x$someuser)))
                            ]
                          )
                        )
                  }
      )
    
        timeblock groupname someuser    V1
    1          1      blue      bob  blue
    2          1      blue    sally  blue
    3          1     green      bob green
    .........
    

    我认为聚合对两者都有好处

    第一部分

    aggregate(Data$groupname,by=list(Data$timeblock,Data$someuser),
         function(x) { 
              ux <- unique(x) 
              ux[which.max(tabulate(match(x, ux)))] })
    

    在R中,“mode”函数返回存储模式,因子变量的存储模式为“numeric”。您可能希望使用
    排序
    ,然后从该结果中输出最后一个。我的示例数据框具有误导性。我把它编辑得更清楚了。
    
        timeblock   username  mostcommongroupforuser
            1          bob     red
            1          sally   red
            1          sue     green
            2          bob     green
            2          sally   blue
            2          sue     red
    
    ddply(Data, .(timeblock, groupname, someuser),
      function(x){as.character(
                        unique(
                          x$groupname[x$someuser==
                                        names(which.max(table(x$someuser)))
                            ]
                          )
                        )
                  }
      )
    
        timeblock groupname someuser    V1
    1          1      blue      bob  blue
    2          1      blue    sally  blue
    3          1     green      bob green
    .........
    
    aggregate(Data$groupname,by=list(Data$timeblock,Data$someuser),
         function(x) { 
              ux <- unique(x) 
              ux[which.max(tabulate(match(x, ux)))] })
    
    aggregate(Data$groupname,by=list(Data$timeblock,Data$someuser),
         function(x) { 
             levels(Data$groupname)[max(as.numeric(x))] })