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.
Asked
Active
Viewed 48 times
-2
-
I"m trying using "which" function but not able to crack the code. – Sherwin Oct 25 '17 at 09:05
-
Try `which.max()`? – Tung Oct 25 '17 at 09:07
-
Can you add some sample data, some sample output and what you've tried so far? – r.bot Oct 25 '17 at 09:30
-
[This](https://stackoverflow.com/questions/17735859/for-each-row-return-the-column-name-of-the-largest-value/17735894) can help. – nghauran Oct 25 '17 at 09:32
1 Answers
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