ruk·si

R
Vectors

Updated at 2017-10-13 14:53

Vector is a list of values. When speaking about vectors, you are usually referring atomic vectors. Lists are also vectors, list vectors, that are covered later. Function c (combine) is used to make vectors.

c(1, 2, 3)
# [1] 1 2 3

Vectors have a single data type. All elements must follow it. Elements will be converted to same type when added.

c(1, TRUE, "three")

You get vector type with typeof().

numbers <- c(1, 2, 3)
typeof(numbers)
# [1] "integer"

Vectors are flat.

c(1, c(2, c(3, 4)))
# [1] 1 2 3 4

Sequences are shorthands for creating vectors.

c(1, 2, 3, 4)
1:4
# [1] 1 2 3 4

5:9
seq(5, 9)
# [1] 5 6 7 8 9

seq(5, 9, 0.5)
# [1] 5.0 5.5 6.0 6.5 7.0 7.5 8.0 8.5 9.0

9:5
# [1] 9 8 7 6 5

You can get first and last elements with head and tail functions.

v <- seq(1, 20)

head(v)
# [1] 1 2 3 4 5 6

tail(v)
# [1] 15 16 17 18 19 20

tail(v, 2)
# [1] 19 20

Vector access indexing starts from 1.

# Assigning vector to variable.
sentence <- c('walk', 'the', 'plank')
sentence[3]
# [1] "plank"

# Changing an element.
sentence[3] <- "dog"
sentence[3]
# [1] "dog"

# Multipoint access.
sentence[c(1, 3)]
# [1] "walk" "dog"

# Range access.
sentence[2:4]
# [1] "the" "dog" "to"

# Range change.
sentence[5:7] <- c('the', 'poop', 'deck')

You can give names to indexes.

ranks <- 1:3
names(ranks) <- c("first", "second", "third")

ranks
# first second  third
#     1      2      3

ranks["first"]
# first
#     1

ranks["third"] <- 333

# Or during creation.
x <- c(first = 1, second = 2, third = 3)

Boolean vectors are useful for filtering vectors.

ships <- c("Blackmoon", "Cherry", "Mondilla", NA)
over.7.chars <- nchar(ships) > 7
ships[over.7.chars]
# [1] "Blackmoon" "Mondilla"

which(over.7.chars)
# [1] "Blackmoon" "Mondilla"

which(is.na(ships), arr.ind=TRUE)
# [1] 4

# Check if all ship names are over 7 characters.
all(nchar(ships) > 7)
# [1] FALSE

# Check if any ship names are exactly 6 characters.
any(nchar(ships) == 6)
# [1] TRUE

Operations applied to a vector is done to each individual elements.

a <- c(1, 2, 3)
a + 1
# [1] 2 3 4

b <- c(4, 5, 6)
a + b
# [1] 5 7 9

a == c(1, 99, 3)
# [1] TRUE FALSE TRUE

a <= c(1, 1, 1)
# [1] TRUE FALSE FALSE

sin(a)
# [1] 0.8414710 0.9092974 0.1411200

Bar plotting vectors.

vesselsSunk <- c(4, 5, 1)
names(vesselsSunk) <- c("England", "France", "Norway")
barplot(vesselsSunk)

Scatter plotting vectors.

x <- seq(1, 20, 0.1)
y <- sin(x)
plot(x, y)

NA values are special.

# Every function should treat NA (not available) specially.
# sum-function notifies about NA values.
a <- c(1, 3, NA, 7, 9)
sum(a)
# [1] NA

# Supress not available values.
sum(a, na.rm = TRUE)
# [1] 20

Sources

  • Google Developers R Programming Videos
  • Try R