Declarations

Typically, compiled languages require that you declare variables; that is, warn the interpreter/compiler of the variables’ existence before using them. This is the case in our earlier C example:

int x;
int y[3];

As with most scripting languages (such as Python and Perl), you do not declare variables in R. For instance, consider this code:

z <- 3

This code, with no previous reference to z, is perfectly legal (and commonplace).

However, if you reference specific elements of a vector, you must warn R. For instance, say we wish y to be a two-component vector with values 5 and 12. The following will not work:

> y[1] <- 5
> y[2] <- 12

Instead, you must create y first, for instance this way:

> y <- vector(length=2)
> y[1] <- 5
> y[2] <- 12

Get The Art of R Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.