Vectors

Table of Contents

Overview

1 + 2 - 3 * 4 / (5 ^ 6)
a <- c(1,2,3,4)
sqrt(a)
exp(a)
log(a)
a <- c(1,2,3)
b <- c(10,11,12,13)
# shows warninging: not a multiple of shorter one
a + b
mean(x)
median(x)
quantile(x)
min(x)
max(x)
range(x)  # c(min(x), max(x))
var(x)
sd(x)
1:3
3:1
seq(1, 3, by = 1)
rep(0, times = 3)
[1] 1 2 3
[1] 3 2 1
[1] 1 2 3
[1] 0 0 0
n <- 3
1:n-1    # === 1:3 - 1
1:(n-1)  # === 1:2
[1] 0 1 2
[1] 1 2
x <- 1:5
x > 3
x[x > 3]
[1] FALSE FALSE FALSE  TRUE  TRUE
[1] 4 5
x[1]
x[3]
x[-2]      # everything except the 2nd element
x[1:3]     # 1st - 3rd elements
x[c(1, 4)] # 1st, and 4th elements

z = c(TRUE, FALSE, TRUE, FALSE, TRUE)
x[z]  # corresponding TRUE elements

The Recycling Rule of Mixed vector and array arithmetic discussion

Calculate the proportion of a subset of a vector howto

mean(rnorm(10) > 0)
[1] 0.4

Generate combinations of vectors' elements howto

First, we can use expand.grid(). In this case, we need to it with apply(A, 1, f) to process each combinations

x = c("foo", "bar", "baz")
y = c(1, 2)
(A = expand.grid(x, y))
  Var1 Var2
1  foo    1
2  bar    1
3  baz    1
4  foo    2
5  bar    2
6  baz    2
apply(A, 1, function(row) {
  x = row[1]
  y = row[2]
  sprintf("%s+%s", x, y)
})
[1] "foo+1" "bar+1" "baz+1" "foo+2" "bar+2" "baz+2"

Or, if you need a single composed vector, you can use outer() as follows:

(B = outer(x, y, FUN = paste))
     [,1]    [,2]   
[1,] "foo 1" "foo 2"
[2,] "bar 1" "bar 2"
[3,] "baz 1" "baz 2"
as.vector(B)
[1] "foo 1" "bar 1" "baz 1" "foo 2" "bar 2" "baz 2"

Or, just use rep(..., each = N) for simple cases:

(xx = rep(x, each = 2))
paste(xx, y)
[1] "foo" "foo" "bar" "bar" "baz" "baz"
[1] "foo 1" "foo 2" "bar 1" "bar 2" "baz 1" "baz 2"