-1

I was given a sample vector v and was asked to use R code to extract, as a number (meaning: not as a character string), the value that was repeated the most times in v.

(Hints: use table(); note that which.max() gives you index of a vector's maximum value, like the maximum value within a table; names() allows you the extract the values of the original vector, when applied to the output of table().)

My answer is as follows: names(which.max(table(v)))

it returns the correct answer as a string, not as a number. Am i using the hint correctly? Thanks.

james black
  • 122
  • 7

1 Answers1

1

names return the number as character, perhaps add as.integer/as.numeric to convert it to number.

as.integer(names(which.max(table(v))))

Moreover, in case of tie which.max would return only the first maximum. If you want all the values which are tied you can use :

v <- c(1, 1, 2, 4, 5, 3, 3)
as.integer(names(which.max(table(v))))
#[1] 1


tab <- table(v)
as.integer(names(tab[max(tab) == tab]))
#[1] 1 3
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213