M_acaron
M_acaron

Reputation: 13

Why does the index in which.max() not match the value of index when I type in the given vector[which.max()]?

Hello I have just started learning R a few weeks ago. Was practicing an exercise where it stated commute times were tracked for one week (just weekdays) and below are the recorded times in min:

commute <- c(17, 16, 20, 24, 18)

I named the vector to its corresponding weekday:

names(commute) <- c("M", "Tu", "W", "Th", "F")

The exercise states: Using diff(), find the day with the greatest change from the previous day.

So I found the day with greatest change to be Friday by writing

which.max(abs(diff(commute)))

But why does it give me Thursday when I type the following?

commute[which.max(abs(diff(commute)))]

How would I be able to adjust this code to print out "F" rather than giving me the index value?

Upvotes: 1

Views: 136

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

diff returns length 1 less than the original vector.

length(commute)
#[1] 5
length(diff(commute))
#[1] 4

So add + 1 to which.max index to get correct value.

commute[which.max(abs(diff(commute))) + 1]
# F 
#18 

Alternatively, if you only want the name ("F") you can extract names from which.max output.

names(which.max(abs(diff(commute))))
#[1] "F"

Upvotes: 3

Related Questions