Vector creation in R
Saving and storing numbers in R is one of the most basic skills but one of the most useful as well. You can assign the number 2
to the variable a
by entering
a <- 2
at the R command line. The “<-” tells R to take the number to the right of the symbol and store it in a variable whose name is given on the left. You can also use the “=” symbol, as in
a = 2
When you make an assignment R does not print out
any information. If you want to see what value a variable has just
type the name of the variable on a line and press the enter key. (In what follows, will display the results as you will see in R, with the R command prompt >
followed by what you type. Lines that begin with a number if brackets such as [1]
are the R output.)
> a [1] 3
This allows you to do all sorts of basic operations and save the numbers:
> b <- sqrt(a*a+3) > b [1] 3.464102
If you want to get a list of the variables that you have defined in a particular session you can list them all using the ls command:
> ls() [1] "a" "b"
You are not limited to just saving a single number. You can create a
list (also called a “vector”) using the c
command (where c
stands for combine):
> a <- c(1,2,3,4,5) > a [1] 1 2 3 4 5 > a+1 [1] 2 3 4 5 6 > mean(a) [1] 3 > var(a) [1] 2.5You can get access to particular entries in the vector in the following manner:
> a <- c(1,2,3,4,5) > a[1] [1] 1 > a[2] [1] 2 > a[0] numeric(0) > a[5] [1] 5 > a[6] [1] NA
Note that the zero entry is used to indicate how the data is stored. The first entry in the vector is the first number, and if you try to get a number past the last number you get “NA.”
Examples of the sort of operations you can do on vectors is given in a next chapter.
To initialize a list of numbers the numeric command can be used. For example, to create a list of 10 numbers, initialized to zero, use the following command:
> a <- numeric(10) > a [1] 0 0 0 0 0 0 0 0 0 0
If you wish to determine the data type used for a variable the type command:
> typeof(a) [1] "double"