# 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 2 3
 3 2 1
 1 2 3
 0 0 0
``````
``````n <- 3
1:n-1    # === 1:3 - 1
1:(n-1)  # === 1:2``````
`````` 0 1 2
 1 2
``````
``````x <- 1:5
x > 3
x[x > 3]``````
`````` FALSE FALSE FALSE  TRUE  TRUE
 4 5
``````
``````x
x
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

• The expression is scanned from left to right.
• Any short vector operands are extended by recycling their values until they match the size of any other operands.
• As long as short vectors and arrays only are encountered, the arrays must all have the same dim attribute or an error results.
• Any vector operand longer than a matrix or array operand generates an error.
• If array structures are present and no error or coercion to vector has been precipitated, the result is an array structure with the common dim attribute of its array operands.

# Calculate the proportion of a subset of a vector howto

• Take advantage of type coercion, alongside `mean()`
``mean(rnorm(10) > 0)``
`````` 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
y = row
sprintf("%s+%s", x, y)
})``````
`````` "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)``
`````` "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)``````
`````` "foo" "foo" "bar" "bar" "baz" "baz"
 "foo 1" "foo 2" "bar 1" "bar 2" "baz 1" "baz 2"
``````