4

I need to find the max value from a list of variables. However, max() returns the contents of the variable instead of the variable name. Is there a way to get the name instead of the content?

Quick example code:

jan <- 0
feb <- 0
mar <- 0

#for testing purposes - just select a random month and add 10
s1 <- sample(1:3, 1)
if (s1==1) {
  jan <- jan + 10
}
if (s1==2) {
  feb <- feb + 10
}
if (s1==3) {
  mar <- mar + 10
}

final <- max(jan, feb, mar)

final

The result from that will always be 10. That isn't helpful... Is there a way to get the month/variable name returned instead? (ie "jan" instead of "10")

Thank you!

jbaums
  • 27,115
  • 5
  • 79
  • 119
jdfinch3
  • 513
  • 1
  • 7
  • 18
  • I also tried adding labels to the list, but the labels are not carried over with max() – jdfinch3 Oct 19 '14 at 08:04
  • 2
    You can name your vector elements to begin with, e.g.: `jan <- c(jan=0); feb <- c(feb=0); mar <- c(mar=0)`, and then `final <- which.max(jan, feb, mar)` will also be named. Access with `names(final)`. – jbaums Oct 19 '14 at 08:22

1 Answers1

8

You could try:

 c("jan", "feb", "mar")[which.max(c(jan, feb, mar))]
 #[1] "jan"
akrun
  • 874,273
  • 37
  • 540
  • 662