-
Notifications
You must be signed in to change notification settings - Fork 24
Functions, Commands, and Arguments
Functions and commands (in this course we usually treat them as the same thing) basically do something to objects. You can think of them as R's verbs. Commands are actions that are done to objects.
For example, let's we create an object x
that is a sequence of numbers 1 through 9.
Numbers <- 1:9
Numbers
## [1] 1 2 3 4 5 6 7 8 9
Imagine that we want to find the mean of Numbers
. To do this we can use the mean
command in base R.
mean(Numbers)
## [1] 5
We can read this command as: Find the mean of the object Numbers.
Notice that after the command mean
we put parentheses ()
around the object. In R all commands and functions are followed by ()
that hold the commands' arguments. If you type ?mean
into the console you will find the docucmentation for the mean
command. In this documentation is a section called Arguments. This tells us what arguments the mean
command can be given. You'll see that the first argument is called x
, which is described as: ''an R object . . .''. In our example we used the object Numbers
.
You can see that the mean
command can take some other arguments such as trim
and na.rm
. In simple commands we don't really need to tell R which argument we are using. R figured out that Numbers
was the x
argument. For more complex commands we should explicitly tell R what which arguments we are using (it also makes the code easier for humans to read). We do this with the equality sign =
. For example,
mean(x = Numbers)
## [1] 5
We saw on the Basic Data in R: Objects and Dataframes page that the assignment operator <-
can be used to assign things to objects. Similarly, we can use <-
to assign the outcome of a command to an object. To assign the mean of x to the new object MeanNumbers
we type:
MeanNumbers <- mean(Numbers)
We can read this as Find the mean of the object Numbers and assign it to the object MeanNumbers.