# Vectors

# Table of Contents

- Overview
- The Recycling Rule of Mixed
`vector`

and`array`

arithmetic - Calculate the proportion of a subset of a vector
- Generate combinations of vectors' elements

# 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
```

```
[1] 1 2 3
[1] 3 2 1
[1] 1 2 3
[1] 0 0 0
```

```
[1] 0 1 2
[1] 1 2
```

```
[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

- 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()`

```
[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

```
Var1 Var2
1 foo 1
2 bar 1
3 baz 1
4 foo 2
5 bar 2
6 baz 2
```

```
[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:

```
[,1] [,2]
[1,] "foo 1" "foo 2"
[2,] "bar 1" "bar 2"
[3,] "baz 1" "baz 2"
```

```
[1] "foo 1" "bar 1" "baz 1" "foo 2" "bar 2" "baz 2"
```

Or, just use `rep(..., each = N)`

for simple cases:

```
[1] "foo" "foo" "bar" "bar" "baz" "baz"
[1] "foo 1" "foo 2" "bar 1" "bar 2" "baz 1" "baz 2"
```