Mike
Mike

Reputation: 1161

Apply a calculation to multiple columns

I've got a table with n columns. I'd like to find the largest value in each column, and then return the value from column CAG that's in the same row. I've managed to do this for column A01, but can you help me apply across all columns?

#My data frame
data <- data.frame(CAG = c(13, 14, 15), A01 = c(6485,35,132), A02 = c(0,42,56))

#My function# applied to work with column A01
result <- data$CAG[data$'A01' == max(data$'A01')]

Upvotes: 1

Views: 323

Answers (1)

Roman Luštrik
Roman Luštrik

Reputation: 70653

You want which.max. Apply it to all columns using sapply.

> data[sapply(data[2:ncol(data)], which.max), ]$CAG
[1] 13 15

Upvotes: 1

Related Questions