Vectors (CloudStat)

November 5, 2011

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




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




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




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




> length(x)

[1] 20

Vectors may have named elements.


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


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


9/5 * temp + 32


> 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

To leave a comment for the author, please follow the link and comment on their blog: CloudStat. 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: , , , ,

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)