Vectors

2020

Creating

c(1, 2, 3, pi, 4)
#> [1] 1.000000 2.000000 3.000000 3.141593 4.000000
1:10
#>  [1]  1  2  3  4  5  6  7  8  9 10

seq: Sequence Generation

seq(0, 3, by = 0.5)
#> [1] 0.0 0.5 1.0 1.5 2.0 2.5 3.0
seq(0, 1, length.out = 11)
#>  [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0

Indexing

library(stringr)
(x <- str_c("x", 1:10))
#>  [1] "x1"  "x2"  "x3"  "x4"  "x5"  "x6"  "x7"  "x8"  "x9"  "x10"
x[3]
#> [1] "x3"

Slicing

x[4:7]
#> [1] "x4" "x5" "x6" "x7"
x[6:length(x)]
#> [1] "x6"  "x7"  "x8"  "x9"  "x10"

Excluding

x[-c(2,8)]
#> [1] "x1"  "x3"  "x4"  "x5"  "x6"  "x7"  "x9"  "x10"
x[-(3:5)]
#> [1] "x1"  "x2"  "x6"  "x7"  "x8"  "x9"  "x10"

Coercion

as.character(1:10)
#>  [1] "1"  "2"  "3"  "4"  "5"  "6"  "7"  "8"  "9"  "10"
as.numeric(c("421", "5", "2.71"))
#> [1] 421.00   5.00   2.71

Math

x <- 1:10
x^2
#>  [1]   1   4   9  16  25  36  49  64  81 100
log(x)
#>  [1] 0.0000000 0.6931472 1.0986123 1.3862944 1.6094379 1.7917595 1.9459101
#>  [8] 2.0794415 2.1972246 2.3025851
x <- seq(0, 2*pi, length.out = 100)
sinx <- sin(x)
cosx <- cos(x)

library(tidyverse)
library(wplot)
tibble(x = x, sin = sinx, cos = cosx) %>%
    pivot_longer(-x, names_to = "Function", values_to = "y") %>%
    ggplot(aes(x, y, colour = Function)) +
        geom_line() +
        theme_wc()