Rodrigo Antunes
Rodrigo Antunes

Reputation: 13

Finding the Max value for a every row in a range of columns

I have a data frame containing some 900 rows and a dozen or so columns. Columns #7 - #11 (so from 7 and up to 11) contain numbers between 0 and 100 inclusive. What I want to know is how I can find:

a) the maximum value of the specified range of columns for each row

b) which column has the max (i.e. column #8 has a value of 100 therefore it contains the highest number)

So, for example, I would like it to return something like: Row #142 has its max value in column #9 or Row #748 has its max value in column #6, etc.

Upvotes: 0

Views: 1264

Answers (2)

akrun
akrun

Reputation: 887118

We can use rowMaxs

library(matrixStats)
index <- 7:11
rowMaxs(as.matrix(df1[, index]))

Or with pmax

do.call(pmax, df1[, index]))

Upvotes: 0

Adam Waring
Adam Waring

Reputation: 1268

index = 7:11

a) max value for a specified range of columns

apply(dataframe[,index], 1, max)

b) max index

apply(dataframe[,index], 1, which.max)

Upvotes: 2

Related Questions