2

I'd started learning R recently and in one of the practice questions, this was asked

What will be the output of mode(c(12, 45, "30", 34*56))

Now, since the numeric data was in majority, I thought the answer would be numeric. But the given answer (which I'd later verified in R console) was character.

What is the reason behind this?

  • 1
    *numeric* can always coerced to *character*. – jogo Nov 16 '18 at 14:13
  • 3
    run ``debugonce(mode)`` and ``mode(c(12, 45, "30", 34*56))`` again for playing with the internals, hence the *why*. – runr Nov 16 '18 at 14:14
  • http://adv-r.had.co.nz/Data-structures.html – hrbrmstr Nov 16 '18 at 14:14
  • @Nutle I'm new to R, basically coding and I really didn't understand what was happening there – John Cleaver Nov 16 '18 at 14:17
  • 1
    @JohnCleaver so it's a useful tool to learn then! You basically enter a debug mode, where you can see the internal code of the function, can run and evaluate the code line by line and see how does the result change. Here, for example, you can try ``is.expression(x)``, ``is.call(x)``, etc, and understand which part will be executed by the ``mode`` function in the end. Finally, just type ``x`` and see how does your input look like, when passed to mode. – runr Nov 16 '18 at 14:22
  • Related, (possible duplicate?) https://stackoverflow.com/questions/8855589/a-comprehensive-survey-of-the-types-of-things-in-r-mode-and-class-and-type – zx8754 Nov 16 '18 at 15:17

1 Answers1

3

R has a hierarchy of returning the mode.

As given in the documentation for mode, (?mode to open its documentation)

"logical", "integer", "double", "complex", "raw", "character", "list", "expression", "name", "symbol" and "function"

gives the way how R returns the mode.

Here, if the vector has even one function, the mode is function. If there is no function present, R checks for symbol and so on.

Moltres
  • 600
  • 4
  • 21