--Managing Vectors

A vector is a sequence of data elements of the same basic type: numericarrow-up-right, characterarrow-up-right, logicalarrow-up-right, factorsarrow-up-right, or datesarrow-up-right (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

  1. Check out the built-in character vector state.name.

  2. How many elements are in this vector?

  3. What attributes does this vector have?

  4. Can you name each vector element with “V1”, “V2”, …, “V50” (shortcut: paste0("v", 1:50))?

  5. Now what attributes does this vector have?

  6. Subset state.name for those elements with the following names: V35, V17, V14, V38.

Last updated