##########################################
################ Hilfe ###################
##########################################

help("exp")
help("lm")
help.search("generalized linear model")
help.start()

##########################################
############## Grundlagen ################
##########################################

# Grundrechenarten

2+5*7

5/3+2

5/(3+2)

5/3^2

(5/3)^2

5%/%3

5%%3

# Mathematische Funktionen

exp(1)

log(exp(1))

sqrt(2)

sin(2*pi)

factorial(4)

choose(10,0)

choose(10,1)

choose(10,2)

# Vergleich von Werten

7 > 3

0.4 + 0.6 == 1

0.3 + 0.6 + 0.1 == 1

1 - 0.3 - 0.6 - 0.1

all.equal(0.3+0.6+0.1, 1)

# Zuweisungsoperatoren

x <- 7

print(x)

x

(x = 7)

(exp(x) -> x)

# Logische Variablen

y <- is.numeric(x)

y

(x <- TRUE)

TRUE == FALSE

# Numerische Datentypen

x <- 7

is.numeric(x)

is.integer(x)

is.double(x)

is.numeric(Inf)

is.numeric(NaN)

# Character

(z <- "A")

(z <- "test")

# Fehlende Werte

is.numeric(NA)

# Logische Operatoren:

x <- 7

x > 1 & x%%2 == 0

x > 1 & x%%2 == 1

x > 1 | x%%2 == 0

x < 1 | x%%2 == 0

# Arbeiten mit Zeichenketten

paste("Das Ergebnis meiner Berechnungen ist: exp(6) = ", exp(6))
paste("Das Ergebnis meiner Berechnungen ist: exp(6) = ", round(exp(6),2))

cat("Das Ergebnis meiner\n Berechnungen ist: exp(6) = ", round(exp(6),2))
paste("Das Ergebnis meiner\n Berechnungen ist: exp(6) = ", round(exp(6),2))

paste("Das Ergebnis meiner Berechnungen ist: exp(6)", round(exp(6),2),
      sep=" = ")
paste(1, 10, "test", sep=", ")

substr("langzeichenkette", start=2, stop=7)
strsplit("langzeichenkette", split="e")

#########################################
############### Vektoren ################
#########################################

# Kombinieren von Elementen

(x <- c(5,2,8,99))

(x <- c(x,3,4))

(y <- c("A","B"))

(z <- c(x,y))

# Eigenschaften eines Vektors

length(z)

mode(z)

mode(x)

# Sequenzen

seq(from=0, to=10, by=2)

seq(from=0, to=10)

seq(to=10)

1:10

# Wiederholungen

rep(0, times=5)

rep(1:3, times=5)

rep(1:3, length=5)

rep(1:3, each=5)

# Zugriff auf Elemente

(x <- 2:10)

x[2]

x[c(1,5,8)]

x[1:5]

x[-1]

x[-c(2,4,5)]

x[x>4]

x[x<5 & x%%2==0]


# Rechnen mit Vektoren

x <- 1:3
y <- 3:1

x+1

x+y

x*y

exp(x)

x^2

x==y

x==y | x>y

x==y & x>y

# Ordnen

(x <- sample(1:10))

sort(x)

order(x)

x[order(x)]

# Auffinden spezieller Elemente

which(x<6 & x%%2==0)

x

#########################################
############### Matrizen ################
#########################################

# Erstellen von Matrizen

(m <- matrix(1:12, ncol=4, nrow=3))

(m <- matrix(1:12, ncol=4, nrow=3, byrow=T))

# Zugriff auf Elemente

m[1,2]

m[,1]

m[2,]

m[2:3,-4]

# Dimension und Typ

dim(m)

mode(m)

# Kombinieren von Vektoren und Matrizen

x <- 1:3
y <- 3:1

(m <- cbind(x,y))

(m <- rbind(x,y))

# Transponieren & Matrixmultiplikation

t(m)

(m2 <- m%*%t(m))

# Inverse

solve(m2)

(m3 <- m2 %*% solve(m2))

round(m3, 3)

# Determinante und Rang

det(m3)

det(m2)

qr(m)$rank

# Diagonalmatrizen

diag(5)

(m <- diag(c(1,2,3)))

diag(m)

# Matrix * Vektor

x <- rep(1,2)

m2%*%x

x%*%m2

# Array

(a <- array(1:24, c(3,2,4)))

a[1,1,1]

#########################################
################ Listen #################
#########################################

# Erstellen von Listen

(l <- list(vector=1:5, char="ABC", mat=matrix(1:4,ncol=2,nrow=2)))

names(l)

# Zugriff auf Elemente

l$char

l[[2]]

#########################################
############# Data Frames ###############
#########################################

# Erzeugen eines Data Frames

(d <- data.frame(v1=c(1,2,3), v2=rep(1,3)))

# Einlesen aus einer Datei

setwd("p:/lehre/abschlussarbeitenkurs")

(d <- read.table("wachstum.raw", header=TRUE))

fix(d)

head(d)

names(d)

# Zugriff auf Variablen

d$BIP

d[[1]]

d[,1]

# Faktorvariablen

d$faktor <- 1 + 1*(d$BIP>0) + 1*(d$BIP>3)

table(d$faktor)

d$faktor <- factor(d$faktor, levels=1:3, labels=c("schlecht", "normal", "gut"))

table(d$faktor)

head(d)

library("car")

d$faktor2 <- recode(d$faktor, "'normal'='gut'")

table(d$faktor2, d$faktor)

#############################################
############# Attribute & Klassen ###########
#############################################

attributes(d)

attributes(m)

attributes(x)


#########################################
############### Grafiken ################
#########################################

# Diskrete Haeufigkeitsverteilungen

pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)
names(pie.sales) <- c("Blueberry", "Cherry", "Apple", "Boston Cream", "Other",
                      "Vanilla Cream")
                      
barplot(pie.sales)
barplot(pie.sales, horiz=TRUE)
pie(pie.sales)
pie(pie.sales, col = c("purple", "violetred1", "green3", "cornsilk", "cyan",
                       "white"))

# Stetige Haeufigkeitsverteilungen:

set.seed(123)
x <- rnorm(100)

# Histogramm
par(mfrow=c(2,2))
hist(x)
hist(x, prob=TRUE)
hist(x, breaks=c(-3,-1.5,0,1.5,3), prob=TRUE)
hist(x, breaks=30, prob=TRUE)

# Kerndichteschätzung
par(mfrow=c(1,1))
plot(density(x), ylim=c(0,0.5), main="Kerndichteschätzung")
hist(x, prob=TRUE, add=TRUE)

# Boxplot
boxplot(x)
boxplot(count ~ spray, data = InsectSprays, col = "lightgray")

# Plot-Typen

par(mfrow=c(2,2))
x <- runif(100, 0, 2*pi)
y <- sin(x)
plot(x, y)

plot(x, y, type="l")

o <- order(x)
x <- x[o]
y <- y[o]

plot(x, y, type="l")
plot(x, y, type="s")

# Plot.Charakter

plot(x,y)
plot(x,y, pch=20)
plot(1:20, 1:20, pch=1:20)
plot(x,y, pch="ü")

# Überschrift & Beschriftung

plot(x, y, main="Sinus", xlab="x-Achse", ylab="y-Achse")
plot(x, y, main="Sinus", xlab="x-Achse", ylab="y-Achse", ylim=c(-2,5),
     xlim=c(1,5))
plot(x, y, main="Sinus", xlab="x-Achse", ylab="y-Achse", ylim=c(-2,5),
     xlim=c(1,5), pch=20, cex=3, cex.axis=0.3, cex.main=2)
plot(x, y, main="Sinus", xlab="x-Achse", ylab="y-Achse", ylim=c(-2,5),
     xlim=c(1,5), pch=20, cex=3, cex.axis=0.3, cex.main=2, col.main="red",
     col="green", col.lab="cyan")

colors()
?colors

# Linientyp & stärke

plot(x, y, type="l", lwd=3)
plot(x, y, type="l", lty=2)
plot(x, y, type="l", lty=3)
plot(x, y, type="l", lty=4)

# Ergänzen von Grafiken

plot(x, y, type="l")
points(x, cos(x))
lines(x, cos(x), lty=2)
text(3, 0, "Test")
arrows(3, 0, 4, 1)
abline(h=0)
abline(v=3)

plot(x, y, type="l")
lines(x, cos(x), lty=2)
polygon(c(x, x[100:1]), c(sin(x), cos(x[100:1])), c(), col="lightgray")

plot(x, y, axes=FALSE)
box()
axis(4)
axis(3, at=c(0,3,5,6), labels=c(-4,3,12,"test"))

# Oberflächen

par(mfrow=c(2,2))

image(t(volcano)[ncol(volcano):1,])

x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))

image(x, y, volcano, col = terrain.colors(100), axes = FALSE)
contour(x, y, volcano, levels = seq(90, 200, by = 5),
        add = TRUE, col = "peru")
axis(1, at = seq(100, 800, by = 100))
axis(2, at = seq(100, 600, by = 100))
box()
title(main = "Maunga Whau Volcano", font.main = 4)

persp(x, y, volcano)
persp(x, y, volcano, ticktype = "detailed", expand = 0.75, d = 100,
      theta = -30, phi = 25)
      
# Grafik abspeichern

pdf("test.pdf")
persp(x, y, volcano)
dev.off()

#########################################
############## Funktionen ###############
#########################################

# Beispiel 1

momente <- function(x, ordnung=2)
  {
  n <- length(x)
  res <- sum(x^ordnung)/n
  return(res)
  }

x <- sample(1:10)

momente(x)

momente(x, ordnung=1)

# Beispiel 2

square <- function(x=2)
  {
  return(x*x)
  }

square(2)

square(x)

# Beispiel 3

hyperfun <- function(x)
  {
  res1 <- momente(x, ordnung=1)
  res2 <- square(x)
  return(list(mittelwert=res1, quadrat=res2))
  }

hyperfun(x)

# Argumente:

momente(x)

momente(ordnung=1, x)

momente(x, 1)

momente(1, x)

pow <- function(x=2, ordnung=length(x))
  {
  return(x^ordnung)
  }

pow(1:3)

pow(1:5)

pow(1:5, ordnung=2)

# ... Argument

hyperfun <- function(x, ...)
  {
  res1 <- momente(x, ...)
  res2 <- square(x)
  return(list(mittelwert=res1, quadrat=res2))
  }

hyperfun(x, ordnung=1)

# Lazy Evaluation

testfun <- function(x, y)
  {
  if(x < 0)
    return(NaN)
  else
    return(y*log(x))
  }

testfun(-1)

testfun(1)

# Verteilungen

pnorm(0, mean=0, sd=1)

pnorm(-2:2, mean=0, sd=2)

pnorm(-1.644854, mean=0, sd=1)

dnorm(0, mean=0, sd=1)

qnorm(c(0.01, 0.025, 0.05, 0.1), mean=0, sd=1)

rnorm(10, mean=0, sd=1)
