[R] Trouble retrieving the second largest value from each row of a data.frame

mpward at illinois.edu mpward at illinois.edu
Sat Jul 24 03:20:29 CEST 2010


I have a data frame with a couple million lines and want to retrieve the largest and second largest values in each row, along with the label of the column these values are in. For example 

row 1
strongest=-11072
secondstrongest=-11707
strongestantenna=value120
secondstrongantenna=value60

Below is the code I am using and a truncated data.frame.  Retrieving the largest value was easy, but I have been getting errors every way I have tried to retrieve the second largest value.  I have not even tried to retrieve the labels for the value yet.

Any help would be appreciated
Mike


> data<-data.frame(value0,value60,value120,value180,value240,value300)
> data
   value0 value60 value120 value180 value240 value300
1  -13007  -11707   -11072   -12471   -12838   -13357
2  -12838  -13210   -11176   -11799   -13210   -13845
3  -12880  -11778   -11113   -12439   -13089   -13880
4  -12805  -11653   -11071   -12385   -11561   -13317
5  -12834  -13527   -11067   -11638   -13527   -13873
6  -11068  -11698   -12430   -12430   -12430   -12814
7  -12807  -14068   -11092   -11709   -11607   -13025
8  -12770  -11665   -11061   -12373   -11426   -12805
9  -12988  -11736   -11137   -12570   -13467   -13739
10 -11779  -12873   -12973   -12537   -12973   -11146
> #largest value in the row
> strongest<-apply(data,1,max)
> 
> 
> #second largest value in the row
> n<-function(data)(1/(min(1/(data[1,]-max(data[1,]))))+ (max(data[1,])))
> secondstrongest<-apply(data,1,n)
Error in data[1, ] : incorrect number of dimensions
>



More information about the R-help mailing list