vectors 

Send to Kindle
home » snippets » r » learn » vectors



Vectors can only have one type of value. If you update a bool vector to include an int, then all values are promoted to ints. If an int vector gets a float, all values becomes floats. If you add a string, then all values become strings.

The c(...) function.

The c function, aka Combine function, creates a vector out of its arguments.

> c(1, 2, 3)
[1] 1 2 3
> c(1, 2.3)
[1] 1.0 2.3
> c(TRUE, FALSE)
[1]  TRUE FALSE
> c(1, 2, TRUE)
[1] 1 2 1
> c(1, 2.0, "string")
[1] "1"      "2"      "string"

The rep function.

> rep("Hello", times=3)
[1] "Hello" "Hello" "Hello"
> x <- rep("Hello", times=3)
> x
[1] "Hello" "Hello" "Hello"
> x[0]
character(0)
> x[1]
[1] "Hello"
> x[2]
[1] "Hello"
> x[3]
[1] "Hello"
> x[4]
[1] NA


# Note: Repeating a single dimension vector gives you a larger single
#   dimension vector.

> x <- 1:3
> x
[1] 1 2 3
> x <- rep(x, times=3)
> x
[1] 1 2 3 1 2 3 1 2 3

The start:end syntax (closed range).

> 1:4
[1] 1 2 3 4
> x <- 1:4
> x[0]
integer(0)
> x[1]
[1] 1
> x[2]
[1] 2
> x[4]
[1] 4
> x[5]
[1] NA

# Note: If start > end, then it's automatically a decending range.

::::r
> 4:1
[1] 4 3 2 1

seq(from, to, by=) to generalize start:end shorthand

> seq(1, 4)
[1] 1 2 3 4
> seq(4, 1)
[1] 4 3 2 1
> seq(1, 4, 2)
[1] 1 3
> seq(1, 4, by=2)
[1] 1 3
> seq(1, by=2, 4)
[1] 1 3
> seq(1, 4, -1)
Error in seq.default(1, 4, -1) : wrong sign in 'by' argument

# Extending a vector.
> x <- 1:3
> x[5]=5
> x
[1]  1  2  3 NA  5
> x[9]=100
> x
[1]   1   2   3  NA   5  NA  NA  NA 100

# Since all values can only be of one type, if you
# assign a different value, then all values are updated.
> x
[1]   1   2   3  NA   5  NA  NA  NA 100
> x[6]=6.6
> x
[1]   1.0   2.0   3.0    NA   5.0   6.6    NA    NA 100.0
> x[7]=TRUE
> x
[1]   1.0   2.0   3.0    NA   5.0   6.6   1.0    NA 100.0
> x[8]="string"
> x
[1] "1"      "2"      "3"      NA       "5"      "6.6"    "1"      "string" "100"

# Indexing
# You can index by a scalar or another vector.
> x[3:6]
[1] "3"   NA    "5"   "6.6"
# So you can index in reverse.
 x[6:3]
[1] "6.6" "5"   NA    "3"


# Named indices.
> names(x)
NULL
> names(x) = c("one", "two")
> x
     one      two     <NA>     <NA>     <NA>     <NA>     <NA>     <NA>     <NA> 
     "1"      "2"      "3"       NA      "5"    "6.6"      "1" "string"    "100" 
> x["two"]
two 
"2" 
> x[2]
two