How to find mode across variables/vectors within a data row in R

后端 未结 3 632
谎友^
谎友^ 2021-01-20 09:55

Does anyone know how to find the mode (most frequent across variables for a single case in R?

For example, if I had data on favorite type of fruit (x), asked nine t

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-20 10:14

    The modeest package provides implements a number of estimators of the mode for unimodal univariate data.

    This has a function mfv to return the most frequent value, or (as ?mfv states) it is perhaps better to use `mlv(..., method = 'discrete')

    library(modeest)
    
    
    ## assuming your data is in the data.frame dd
    
    apply(dd[,2:6], 1,mfv)
    [1] 5 7 4 2
    ## or
    apply(dd[,2:6], 1,mlv, method = 'discrete')
    [[1]]
    Mode (most frequent value): 5 
    Bickel's modal skewness: -0.2 
    Call: mlv.integer(x = newX[, i], method = "discrete") 
    
    [[2]]
    Mode (most frequent value): 7 
    Bickel's modal skewness: -0.4 
    Call: mlv.integer(x = newX[, i], method = "discrete") 
    
    [[3]]
    Mode (most frequent value): 4 
    Bickel's modal skewness: -0.4 
    Call: mlv.integer(x = newX[, i], method = "discrete") 
    
    [[4]]
    Mode (most frequent value): 2 
    Bickel's modal skewness: 0.4 
    Call: mlv.integer(x = newX[, i], method = "discrete") 
    

    Now, if you have ties for the most frequent, then you need to think about what you want.
    both mfv and mlv.integer will return all the values that tie for the most frequent. (although the print method only shows a single value)

提交回复
热议问题