# Vectors (CloudStat)

November 5, 2011
By

(This article was first published on CloudStat, and kindly contributed to R-bloggers)

The simplest type of data object in R is a vector, which is simply an ordered set of values. Some further examples of creating vectors are shown below:

Input:

1:20

Output:

 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

This creates a numeric vector containing the elements 1 to 20. The “:” is a shorthand for the explicit command, seq(from=11, to=20, by=1). Vectors can be assigned a name (case sensitive) via the assignment operator (“=”), for example:

x = 1:20y = c(63, 24, 39, 41, 96) # "c" means "combine"z = c("banana", "lion", "spoon")

Note: The “#” can be used to make comments in your code. R ignores anything after it on the same line.

To display a vector, use its name. To extract subsets of vectors, use their numerical indices with the subscript operator “[” as in the following examples.

Input:

zx[4]y[c(1,3,5)]

Output:

> z
[1] "banana" "lion"   "spoon"
> x[4]
[1] 4
> y[c(1,3,5)]
[1] 63 39 96

The number of elements and their mode completely define the data object as a vector.

The class of any vector is the mode of its elements:

Input:

class(c(T,T,F,T))class(y)

Output:

> class(c(T,T,F,T))
[1] "logical"
> class(y)
[1] "numeric"

The number of elements in a vector is called the length of the vector and can be
obtained for any vector using the length function:

Input:

length(x)

Output:

> length(x)
[1] 20

Vectors may have named elements.

Input:

temp = c(11, 12, 17)names(temp) = c("London", "Madrid", "New York")temp

Output:

> temp = c(11, 12, 17)
> names(temp) = c("London", "Madrid", "New York")
> temp
11       12       17

Operations can be performed on the entire vector as a whole without looping through each element. This is important for writing efficient code as we will see later. For example, a conversion to Fahrenheit can be achieved by:

Input:

9/5 * temp + 32

Output:

> 9/5 * temp + 32
51.8     53.6     62.6


#3 Vectors Example

Source: An Introduction to R: Examples for Actuaries by Nigel De Silva

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...