This is my data.frame/data.table
library(data.table)
df<- fread('
A B C D SecondLargest
1 3 2 4 B
6 3 5 4 C
7 3 7 1 A
6 9 3 2 A
')
I am trying to extract the column name with second largest value(in parallel) in my "SecondLargest" desried column.
I have tried with no success.
df[,SecondLargest:= colnames(df[,c(1:4),
with=FALSE])[apply(df[,c(1:4),with=FALSE],1,function(x)
x[rank(1/x, ties.method='first')==2])]]
I am ok with both first or last type of tie breaker. You help is highly appreciated!
df$SecondLargest <- apply(df, 1, function(x){names(which(x == sort(x)[3]))[1]})
– alistaire