"R is not just a statistics package,
it's a flexible and powerful language"
Vector (aka mother of all data structures)
# Skalar?
x <- 5
# First element
x[1]
## [1] 5
# Everything is an object
class(x)
## [1] "numeric"
nm <- c("Peter", "Bender")
nr <- c(2, 4)
paste("Hi", nm, "your id is", nr)
## [1] "Hi Peter your id is 2" "Hi Bender your id is 4"
data frame (aka workhorse)
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
# df[rows, columns]
mtcars[mtcars$gear == 4, c("cyl", "gear")]
## cyl gear
## Mazda RX4 6 4
## Mazda RX4 Wag 6 4
## Datsun 710 4 4
## Merc 240D 4 4
## Merc 230 4 4
## Merc 280 6 4
## Merc 280C 6 4
## Fiat 128 4 4
## Honda Civic 4 4
## Toyota Corolla 4 4
## Fiat X1-9 4 4
## Volvo 142E 4 4
apply family or how to loop
# extraordinary
l <- list()
for(i in 1:4){
l[[i]] <- sqrt(i)
}
l
## [[1]]
## [1] 1
##
## [[2]]
## [1] 1.414214
##
## [[3]]
## [1] 1.732051
##
## [[4]]
## [1] 2
# apply family
l <- lapply(1:4, sqrt)
l
## [[1]]
## [1] 1
##
## [[2]]
## [1] 1.414214
##
## [[3]]
## [1] 1.732051
##
## [[4]]
## [1] 2