Database Reference
In-Depth Information
Vectors
Vectors are a basic building block for data in R. As seen previously, simple R
variables are actually vectors. A vector can only consist of values in the same class.
The tests for vectors can be conducted using the is.vector() function.
is.vector(i)
# returns TRUE
is.vector(flag)
# returns TRUE
is.vector(sport)
# returns TRUE
R provides functionality that enables the easy creation and manipulation of
vectors. The following R code illustrates how a vector can be created using the
combine function, c() or the colon operator, : , to build a vector from the sequence
of integers from 1 to 5. Furthermore, the code shows how the values of an existing
vector can be easily modified or accessed. The code, related to the z vector,
indicates how logical comparisons can be built to extract certain elements of a
given vector.
u <- c("red", "yellow", "blue") # create a vector "red"
"yellow" "blue"
u # returns "red" "yellow" "blue"
u[1] # returns "red" (1st element in u)
v <- 1:5 # create a vector 1 2 3 4 5
v # returns 1 2 3 4 5
sum(v) # returns 15
w <- v * 2 # create a vector 2 4 6 8 10
w # returns 2 4 6 8 10
w[3] # returns 6 (the 3rd element of w)
z <- v + w # sums two vectors element by element
z # returns 3 6 9 12 15
z > 8 # returns FALSE FALSE TRUE TRUE TRUE
z[z > 8] # returns 9 12 15
z[z > 8 | z < 5]
# returns 3 9 12 15 ("|" denotes "or")
Sometimes it is necessary to initialize a vector of a specific length and then
populate the content of the vector later. The vector() function, by default,
creates a logical vector. A vector of a different type can be specified by using the
mode parameter. The vector c , an integer vector of length 0, may be useful when
Search WWH ::




Custom Search