Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R - How to get max() to return variable names instead of contents of the variables?

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!

like image 821
jdfinch3 Avatar asked Feb 11 '23 18:02

jdfinch3


1 Answers

You could try:

 c("jan", "feb", "mar")[which.max(c(jan, feb, mar))]
 #[1] "jan"
like image 140
akrun Avatar answered Feb 14 '23 11:02

akrun