r - Returning 1st Largest and 2nd Largest numbers -
df <- b c d e f g h 0 1 2 3 4 5 6 7 1 2 3 8 5 6 7 4 need find 1st , 2nd largest number in above given data frame . result should below .
a b c d e f g h 1st largest 2nd largest 0 1 2 3 4 5 6 7 7 6 1 2 3 8 5 6 7 4 8 7
we can loop through rows using apply (with margin=1), sort elements decreasing=true option, , first 2 elements head or [1:2], transpose output , assign create 2 new columns in 'df'.
df[c("firstlargest", "secondlargest")] <- t(apply(df, 1, function(x) head(sort(x, decreasing=true),2))) df # b c d e f g h firstlargest secondlargest #1 0 1 2 3 4 5 6 7 7 6 #2 1 2 3 8 5 6 7 4 8 7
Comments
Post a Comment