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:20

y = 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:

z

x[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

London Madrid New York

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

London Madrid New York

51.8 53.6 62.6

#3 Vectors Example

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

*Related*

To

**leave a comment** for the author, please follow the link and comment on their blog:

** CloudStat**.

R-bloggers.com offers

**daily e-mail updates** about

R news and

tutorials on topics such as:

Data science,

Big Data, R jobs, visualization (

ggplot2,

Boxplots,

maps,

animation), programming (

RStudio,

Sweave,

LaTeX,

SQL,

Eclipse,

git,

hadoop,

Web Scraping) statistics (

regression,

PCA,

time series,

trading) and more...

If you got this far, why not

__subscribe for updates__ from the site? Choose your flavor:

e-mail,

twitter,

RSS, or

facebook...

**Tags:** data structure, guide, newbie, R, vectors