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

前端 未结 3 1556
刺人心
刺人心 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条回答
  •  离开以前
    2020-12-21 06:50

    You can combine this function for finding the mode with aggregate.

    Mode <- function(x) {
      ux <- unique(x)
      ux[which.max(tabulate(match(x, ux)))]
    }
    
    aggregate(someuser ~ groupname, Data, Mode)
    
      groupname someuser
    1         a        x
    2         b        x
    3         c        x
    

    Note that in the event of a tie, it will only return the first value.

提交回复
热议问题