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 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)
#  "integer"
``````

Vectors are flat.

``````c(1, c(2, c(3, 4)))
#  1 2 3 4
``````

Sequences are shorthands for creating vectors.

``````c(1, 2, 3, 4)
1:4
#  1 2 3 4

5:9
seq(5, 9)
#  5 6 7 8 9

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

9:5
#  9 8 7 6 5
``````

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

``````v <- seq(1, 20)

#  1 2 3 4 5 6

tail(v)
#  15 16 17 18 19 20

tail(v, 2)
#  19 20
``````

Vector access indexing starts from 1.

``````# Assigning vector to variable.
sentence <- c('walk', 'the', 'plank')
sentence
#  "plank"

# Changing an element.
sentence <- "dog"
sentence
#  "dog"

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

# Range access.
sentence[2:4]
#  "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]
#  "Blackmoon" "Mondilla"

which(over.7.chars)
#  "Blackmoon" "Mondilla"

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

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

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

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

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

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

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

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

sin(a)
#  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)
#  NA

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

# Sources

• Google Developers R Programming Videos
• Try R