--Managing Vectors
A vector is a sequence of data elements of the same basic type: numeric, character, logical, factors, or dates (exclude: two additional vector types - complex and raw)
#Creating Vectors
Four main ways to create a vector: :, c(), seq(), rep()
# integer vector
w <- 8:17
w
## [1] 8 9 10 11 12 13 14 15 16 17
# double precision floating point (number with decimals) vector
x <- c(0.5, 0.6, 0.2)
x
## [1] 0.5 0.6 0.2
# logical vector
y <- c(TRUE, FALSE, FALSE)
y
## [1] TRUE FALSE FALSE
# Character vector
z <- c("a", "b", "c")
z
## [1] "a" "b" "c"#Coercing Vectors
When you attempt to combine different types of elements (i.e. character and numeric) they will be coerced to the most flexible type possible:
#Adding on to Vectors
#Adding Attributes to Vectors
#Subsetting Vectors
Subsetting with positive integers:
Subsetting with negative integers:
Subsetting with logical values:
Subsetting with names:
Simplifying vs. Preserving:
Simplifying subsets returns the simplest possible data structure that can represent the output. Preserving subsets keeps the structure of the output the same as the input.
#Exercises
Check out the built-in character vector
state.name.How many elements are in this vector?
What attributes does this vector have?
Can you name each vector element with “V1”, “V2”, …, “V50” (shortcut:
paste0("v", 1:50))?Now what attributes does this vector have?
Subset
state.namefor those elements with the following names: V35, V17, V14, V38.
Last updated