More R Key Actions
This page has the following sections:
There are two possible results from a function:
- It can return a value
- It can produce one or more side effects
mean function returns a value, and it has no side effects.
plot function has the side effect of creating a plot on the current graphics device. If there is not an active graphics device in the current session, it also has the side effect of starting one.
Note that “value” is singular. A function will return only one object (though that object may have many components).
The three types of function are:
- standard functions
- assignment functions
Here is a small example:
> x <- runif(26) + 5 > names(x) <- letters
This example has one of each type of function.
runif is a typical function — it is called by following its name with arguments surrounded by parentheses.
+ is an operator. In this case it is a binary operator — it appears between its two arguments.
The use of
names in this case is as an assignment function. It appears on the left of the assignment operator. It is precipitating a change to an existing object rather than creating a new object.
There are only a select few functions that can be used as assignment functions.
There is one particular function that novices tend to try to use as an assignment function that may not be. The attempt boils down to something like:
> paste("x", 1, sep="") <- 1 # WRONG
(In the context where this comes up, the advice is generally to create one list rather than a number of individual objects.)
Operators in R have a precedence order — some are done before others.
For example in the command:
> 4 * 3 + 8 / 2  16
the multiplication (*) and division (/) are done before the addition.
If you want the addition done first, then use parentheses:
> 4 * (3 + 8) / 2  22
If you aren’t sure of the precedence, then use parentheses.
You can see the precedence table with the command:
Here we meet three types of simple data creation. These are done with:
c function combines values into a vector:
> x <- c(4, 84, -318, 22)
: operator creates simple sequences. For example:
> x <- 3:12
creates a vector containing each integer from 3 to 12, inclusive. The
seq function is more flexible in the sequences it produces.
rep function creates repetitions. For instance:
> x <- rep(1:2, 10)
creates a vector of length 20 whose elements alternate between 1 and 2.
This includes a discussion of functions, of looping and control structures, of subscripting, and many other topics.
Back to top level of Impatient R