This section introduces the basic operations on vectors, most of which are done element-wise. Please pay attention to the recycling of vectors (usually, recycling doesn't generate an error or a warning, so it is easy to miss if it was unintended), missing values (NA), and logical vectors often used for data subsetting.
Vectors and assignment
R operates on named data structures. The simplest such
structure is the numeric vector, which is a single entity
consisting of an ordered collection of numbers. To set up a vector
named x
, say, consisting of five numbers, namely 10.4, 5.6, 3.1,
6.4 and 21.7, use the R command
> x <- c(10.4, 5.6, 3.1, 6.4, 21.7)
This is an assignment statement using the function
c()
which in this context can take an arbitrary number of vector
arguments and whose value is a vector got by concatenating its
arguments end to end.
A number occurring by itself in an expression is taken as a vector of length one.
Notice that the assignment operator ('<-
'), which consists
of the two characters '<
' ("less than") and
'-
' ("minus") occurring strictly side-by-side and it
'points' to the object receiving the value of the expression.
In most contexts the '=
' operator can be used as an alternative.
Assignment can also be made using the function assign()
. An
equivalent way of making the same assignment as above is with:
> assign("x", c(10.4, 5.6, 3.1, 6.4, 21.7))
The usual operator, <-
, can be thought of as a syntactic
short-cut to this.
Assignments can also be made in the other direction, using the obvious change in the assignment operator. So the same assignment could be made using
> c(10.4, 5.6, 3.1, 6.4, 21.7) -> x
If an expression is used as a complete command, the value is printed and lost. So now if we were to use the command
> 1/x
the reciprocals of the five values would be printed at the terminal (and
the value of x
, of course, unchanged).
The further assignment
> y <- c(x, 0, x)
would create a vector y
with 11 entries consisting of two copies
of x
with a zero in the middle place.
Source: R Core Team, https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Simple-manipulations-numbers-and-vectors
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 License.