The following is a script file containing all R code of all sections in this slide set.

Basic Interaction

1+3/5*6^2
rnorm(5,mean=30,sd=10) 
# function composition example
mean(sample(1:1000,30)) 
plot(sample(1:10,5),sample(1:10,5),
     main="Drawing 5 random points",xlab="X",ylab="Y")

Variables and Objects

vat <- 0.20
priceVAT <- 240 * (1 + vat)
k <- 10
g <- k/2
x <- g*2
x <- 23^3
x
x <- true
x <- 23
x
x <- 4
x

Vectors

prices <- c(32.4,35.4,30.2,35,31.99)
prices
prices <- c(worten=32.4,fnac=35.4,mediaMkt=30.2,radioPop=35,pixmania=31.99)
prices
barplot(prices)

Indexing

prices <- c(worten=32.4,fnac=35.4,
            mediaMkt=30.2,radioPop=35,pixmania=31.99) 
prices[3]
prices <- c(worten=32.4,fnac=35.4,
            mediaMkt=30.2,radioPop=35,pixmania=31.99) 
prices["worten"]
prices[worten]
prices <- c(worten=32.4,fnac=35.4,
            mediaMkt=30.2,radioPop=35,pixmania=31.99) 
prices[c(2,4)]
prices[c("worten","pixmania")]
prices[prices > 35]
prices[prices > mean(prices)]

Vectorization

vat <- 0.23
(1+vat)*prices
sqrt(prices)
prices2 <- c(worten=32.5,fnac=34.6,mediaMkt=32,
             radioPop=34.4,pixmania=32.1)
prices2
(prices+prices2)/2
prices > 35

Matrices

prc <- matrix(c(32.40,35.40,30.20, 35.00, 31.99, 
                32.50, 34.60, 32.00, 34.40, 32.01),
              nrow=2,ncol=5,byrow=TRUE)
prc
prc <- matrix(c(32.40,35.40,30.20, 35.00, 31.99, 
                32.50, 34.60, 32.00, 34.40, 32.01),
              nrow=2,ncol=5,byrow=TRUE)
prc
prc
prc[2,4]
prc[1,]
prc[,2]
colnames(prc) <- c("worten","fnac","mediaMkt","radioPop","pixmania")
rownames(prc) <- c("porto","lisboa")
prc
prc["lisboa",]
prc["porto","pixmania"]

Lists

lst <- list(id=12323,name="John Smith",
            grades=c(13.2,12.4,5.6))
lst
lst$grades
lst[c('name','grades')]
lst[[2]]
lst[2]

Data Frames

stud <- data.frame(nrs=c("43534543","32456534"),
                   names=c("Ana","John"),
                   grades=c(13.4,7.2))
stud
stud <- edit(stud)
stud
stud[2,3]
stud[1,"names"]
stud[1:2,]
stud[,c("names","grades")]
stud[stud$grades > 13,"names"]
stud[stud$grades <= 9.5, c("names","grades")]
subset(stud,grades > 13,names)
subset(stud,grades <= 9.5,c(nrs,names))