-2

I'm working on a R code. I have a dataset which has Product(variables) and under it I have its annual spendings for 10 years. Now I want to do a row - wise search and find the max annual spending and extract that max value's variable/field name.

1 Answers1

0

I would approch the problem as follows assuming each variable makes its own column in an R data.frame df. first extract the max Value for each row

(Clarification: I am using the pip operator "%>%" from the package dplyr)

maxRow <- sapply(t(df) %>% as_data_frame(),max)

then collect the column name containing the max value for each row

sapply(1:nrow(df),function(idx){names(df)[df[idx,] == maxV[idx]]})

alternatively usig thecatalyst suggestion just do:

sapply(1:nrow(df),function(idx){which.max(df[idx,]) %>% names()})
Bertil Baron
  • 4,923
  • 1
  • 15
  • 24