Comparing the values at each position in each vector -> Bigger, smaller: returns boolean
u <- c(5,2,8)
v <- c(1,3,9)
u>v
## [1] TRUE FALSE FALSE
Creating and comparing own vectors: is two bigger than one?
one <- c(8561, 9416, 98451)
two <-c(2465,98435,32)
one < two
## [1] FALSE TRUE FALSE
the below function takes the vector (u) as argument as returns u + 1: 5 becomes 6, 2 becomes 6, and so on…
w <- function(x) return(x+1)
w(u)
## [1] 6 3 9
same principle with vector v:
w(v)
## [1] 2 4 10
the below function squares the argument (the input vector) and adds 1:
m <- function(x) return(x**2+1)
m(u)
## [1] 26 5 65
-> 5 becomes 26 and so on…
same with vector v:
m(v)
## [1] 2 10 82
1 becomes 2…
Now create a functions that returns x^2 -1:
Z <- function(x) return(x**2-1)
Z(u)
## [1] 24 3 63
-> 5 becomes 24 and so on…
rouding to nearest integer:
y <- c(1.2,3.9,0.4)
z <- round(y)
z
## [1] 1 4 0
Let’s apply the function for rounding to the nearest integer to an example vector r<-c(0.25,0.9,2.1,4.7,5.1):
r<-c(0.25,0.9,2.1,4.7,5.1)
x <- round(r)
x
## [1] 0 1 2 5 5
applying function to two arguments (sequence and integer):
f<-function(x,c) return((x+c)^2)
f(1:3,0)
## [1] 1 4 9
same thing - different numbers
f(1:3,1)
## [1] 4 9 16
Create a function that returns (x-c)^2 and calculate f(1:3,0) and f(1:3,1):
k <- function(x,c) return((x-c)^2)
k(1:3,0)
## [1] 1 4 9
k(1:3,1)
## [1] 0 1 4
z12 <- function(z) return(c(z,z^2))
function returns matrix: raw value and squared value concatanated
x <- 1:8
z12(x)
## [1] 1 2 3 4 5 6 7 8 1 4 9 16 25 36 49 64
Compute z12(x2) where x2<-1:5. Explain the output.
x2<-1:5
z12(x2)
## [1] 1 2 3 4 5 1 4 9 16 25
-> the raw values (1 to 5) are concatenated with the squared values (4 to 25)
output of z12 can be shown as matrix:
matrix(z12(x),ncol=2)
## [,1] [,2]
## [1,] 1 1
## [2,] 2 4
## [3,] 3 9
## [4,] 4 16
## [5,] 5 25
## [6,] 6 36
## [7,] 7 49
## [8,] 8 64
Create a similar matrix using z12(x2)
matrix(z12(x2),ncol=2)
## [,1] [,2]
## [1,] 1 1
## [2,] 2 4
## [3,] 3 9
## [4,] 4 16
## [5,] 5 25
x <- c(88,NA,12,168,13)
x
## [1] 88 NA 12 168 13
mean function cannot calculate with NA -> output: na
mean(x)
## [1] NA
telling mean function to ingnore/remove NAs:
mean(x,na.rm=T)
## [1] 70.25
-> successfully calculates mean
x <- c(88,NULL,12,168,13)
mean(x)
## [1] 70.25
-> while NAs break the caculations, NULL values are ignored by default and do not hinder calculations
mode returns the datatype:
x <- c(5,NA,12)
mode(x[1])
## [1] "numeric"
mode(x[2])
## [1] "numeric"
y <- c("abc","def",NA)
mode(y[2])
## [1] "character"
mode(y[3])
## [1] "character"
The four cells above show that NAs are stored with different datatypes based on what datatype the other values within the vectors have. -> NA surrounded by numbers is stored with the numeric datatype -> NA surrounded by characters is stored as character