-3

I was wondering if there was an underlying programming logic as to why some basic R functions behave differently towards raw data input into them vs. vectors.

For example, if I do this

mean(1,2,3)

I don't get the correct answer, and don't get an error

But if I do this

sum(1,2,3)

I do get the right answer, even though I'd assume proper syntax would be sum(c(1,2,3))

And if I do this

sd(1,2,3)

I get an error Error in sd(1, 2, 3) : unused argument (3)

I'm interested into what, if any, the underlying programming logic of these different behaviors are. (I'm sure if I rooted around in the source code I could figure out exactly why they behave differently, but I want to know if there is a reason why the code might have been written that way).

Practically, I'm teaching a basic R class and want to explain to my students why things work that way; they get a bit tired of me saying "That's just how R works, live with it; and always put things in vectors to make life easy."

EDITS: I have bolded some sections to add emphasis. My question is largely about software design, not how these particular function happen to operate or how to determine their exact operation. That is, not "what arguments do these functions accept" but "why do simple mathematical functions in R appear (to a biologist) to have been designed differently".

N Brouwer
  • 4,778
  • 7
  • 30
  • 35
  • 5
    Did you read documentation I wonder.... `mean` accepts a vector `x`, while all the rest of the places are for arguments. While `sum` accepts as many vectors as you wish (e.g., you can even do `sum(1:3, 5:6)`) and it has only one hard-coded argument which needs to be specifically specified (`na.rm`). R has absolutely great documentation compared to other languages. You can simply invoke it from console using `?sum` or `help("sum")`- please use this great feature. – David Arenburg Sep 20 '16 at 14:26
  • 1
    Hint: what is the difference in placement of `...` between `sum(...,` and `mean(x, ...` – Chris Sep 20 '16 at 14:35
  • 1
    My question is not about the mechanics of the function. I can read the documentation just fine, thank you. I am curious as to whether there is an underlying logic based on some programming principal, R ethic, or other factor as to why these function behave differently b/c students in my class find these different behaviors hard to understand. – N Brouwer Sep 20 '16 at 15:54

1 Answers1

2

the second argument taken by mean is trim, which is not a listed argument for sum. the first argument for sum is \dots, so, I believe, the function will try to compute the sum of all values entered as unnamed arguments.

mean and sum are generic functions, so they get deployed differently depending on an object's class.

mkearney
  • 1,266
  • 10
  • 18
  • Thank you for your answer. This helps me understand a bit better as to what the designers of R are attempting to do. – N Brouwer Sep 20 '16 at 15:55