Search code examples
rapplyfrequency

I Want Frequency Value with the Maximum Sample Using R


I want the frequency with the maximum samples in df

df <- data.frame(Freq = c(1,2,3,4,5,6,7,8,9,10), Valu = c(10,5,11,7,13,15,9,6,12,12))


apply(df, 2, which.max)

.

What I want

I want it to print just the frequency of the maximum Valu which is 6


Solution

  • We could use which.max on the column 'Sample', get the index and extract ([), the corresponding 'Freq' value

    with(df, Freq[which.max(Valu)])
    #[1] 6
    

    If the column names are changing, then use position index

    df[[1]][which.max(df[[2]])]
    [1] 6
    

    Or may use order as well

    df[[1]][order(-df[[2]])][1]
    [1] 6
    

    If we loop over the columns (*apply) with MARGIN = 2 and apply the function which.max, it returns the index of max for those columns separately