Homo Deus A Brief History of Tomorrow
Homo Deus A Brief History of Tomorrow
Homo Deus A Brief History of Tomorrow
R Programming
J. R. Shrestha
November 2016
1 / 19
Basics
2 / 19
Example
r <- 30.5861
2*r -> h
assign( "volume", round(2*pi*r*(r+h), 2) )
volume
5 / 19
Data Types in R
Example
x <- 87.9
y <- "123.45"
typeof(x); typeof(y)
z <- x + as.double(y)
is.double(z)
7 / 19
Data Type: Integer
Example 1 Example 2
m = 20 n = as.integer(20)
is.integer(m) is.integer(n)
typeof(m) typeof(n)
8 / 19
Data Structures: Vector
An ordered collection of objects of the same type
All doubles or all integers or all logical etc.
A single numeric variable in R is regarded as a vector of length one
Can be created by combining similar variables using the function
c(...) or other alternatives [seq(), rep(), etc.]
Examples
x <- c(8.5, 7.3, 6.9, 5.4)
y <- 1:5
z <- c(rev(x), 0, y)
s <- seq(from=-3, to=3, by=0.5)
t <- seq(from=0, to=pi, length=17)
r1 <- rep(1:4, 4)
r2 <- rep(1:4, c(2,1,3,4))
r3 <- rep(1:4, 4:1)
9 / 19
Vector Calculations
Calculations when done on vectors are done element-wise
v1 <- c(10, 20, 30, 40, 50)
v2 <- c(1, 2, 3, 4, 5)
v <- v1 + v2
* estimated worldwide totals of carbon emissions that resulted from fossil fuel use
[Marland et al., 2003]
The objects Year and Carbon are vectors which are each formed by
combining separate numbers together
The construct Carbon~Year is a graphics formula
The plot() function interprets it to mean ”plot Carbon as a function
of Year”
pch is a setting which means plot character
11 / 19
Data Structure: Factors
Used to represent categorical data
Data values represented by numerical codes
Also called ‘enumerated type’ or ‘category’
Example
g1 <- c("male", "male", "female", "male", "female")
g2 <- factor(g1)
g3 <- factor(g1, levels=c("male", "female"))
typeof(g1)
typeof(g2) data.class(g2)
is.integer(g2) is.factor(g2)
levels(g2) levels(g3)
as.integer(g2) as.integer(g3)
Example
t1 <- c("medium", "high", "low", "high", "low")
t2 <- ordered(t1, levels = c("low", "medium", "high"))
table(t2)
Example 2
g1 <- sample(c("male", "female"), size=20, replace=TRUE)
g2 <- factor(g1, levels=c("male", "female"))
s1 <- rnorm(20, mean=50000, sd=10000)
s2 <- trunc(s1)
DF <- data.frame(g2, s2)
names(DF) <- c("gender", "salary")
15 / 19
Data Structure: Matrix
16 / 19
Creating Matrices
By changing the dimension using dim()
> x <- 1:8
> dim(x) <- c(2, 4)
> x
[,1] [,2] [,3] [,4]
[1,] 1 3 5 7
[2,] 2 4 6 8