David
David

Reputation: 47

Using max() function in r to return value and its name in vector?

I need to return the max value in a vector along with the index name. Day and stock price. Desired output: Fri 34

v.stock.prices <- c(23,27,23,21,34)
names(v.stock.prices) <- c('Mon','Tues','Wed','Thurs','Fri')
max.price <- max(v.stock.prices)
print(max.price)

I get only 34 as output, how can I also return its index?

Upvotes: 2

Views: 848

Answers (2)

akrun
akrun

Reputation: 887851

We can also use ==

v.stock.prices[v.stock.prices == max(v.stock.prices)]

Upvotes: 0

tmfmnk
tmfmnk

Reputation: 40171

You can do:

v.stock.prices[which.max(v.stock.prices)]

Fri 
 34

Upvotes: 4

Related Questions