Is there something like pmax index?

I have a data frame with the following data:

date=strptime(c(20110101,20110102,20110103,20110104,20110105,20110106),'%Y%m%d')
rate1=c(1,2,3,4,5,6)
rate2=c(2,1,3,6,8,4)
rate3=c(4,1,3,6,8,3)
rate4=c(7,8,9,2,1,8)
z=data.frame(date,rate1,rate2,rate3,rate4)
z$max=pmax(rate1,rate2,rate3,rate4)

The pmax function allows me to get the maximum value for this record, but I was wondering how I can get the maximum value index for this record.

Where z $ max will be equal 7,8,9,6,8,8, I would like to get5,5,5,3,3,5

Is it possible? I know this seems simple, but I canโ€™t find the answer anywhere.

+5
source share
2 answers

Very simple in the R database:

z$wmax <- apply(z[, -c(1,6)],1, which.max)

In fact, this gives you less than you requested, since I excluded the first column, but this can be easily fixed by adding it.

z$max_col_n <- apply(z[, -c(1,6)],1, which.max) +1
+3
source

You can use max.col:

> z$max = max.col(z[2:5])+1
> z
        date rate1 rate2 rate3 rate4 max
1 2011-01-01     1     2     4     7   5
2 2011-01-02     2     1     1     8   5
3 2011-01-03     3     3     3     9   5
4 2011-01-04     4     6     6     2   3
5 2011-01-05     5     8     8     1   3
6 2011-01-06     6     4     3     8   5

, , , 4 , , , , , 1.

+13

All Articles