How to aggregate data in R with mode (most common) value for each row?

前端 未结 3 1560
刺人心
刺人心 2020-12-21 06:34

I have a data set for example,

Data <- data.frame(
  groupname = as.factor(sample(c(\"a\", \"b\", \"c\"), 10, replace = TRUE)),
  someuser = sample(c(\"x\         


        
3条回答
  •  Happy的楠姐
    2020-12-21 06:42

    Many options. Here one using table to compute frequency and which.max to select max occurred. within data.table framework:

    library(data.table)
    setDT(Data)[,list(someuser={
      tt <- table(someuser)
      names(tt)[which.max(tt)]
    }),groupname]
    

    using plyr( nearly the same) :

    library(plyr)
    ddply(Data,.(groupname),summarize,someuser={
      tt <- table(someuser)
      names(tt)[which.max(tt)]
    })
    

提交回复
热议问题