### Jürgen Kampf
### Stochastics III
### Introduction in Vectors and Data Frames
## THIS FILE SHOULD BE OPENED IN R USING THE MENU ITEM File - Open script.
## BY PRESING THE F5-BUTTON YOU CAN COPY LINES FROM THIS SCRIPT INTO THE
## CONSOLE.
### There are different ways to define a vector
# Enumerating its elements
c(0,1,3)
# All numbers from 1 to 10
y=1:10
y
# Several (here: 4) times the same number (here: 45)
z=rep(45,4)
z
# One vector as the concatination of two (or more) vectors
c(y,z)
### Elements and Subvectors
# There are different ways to extract a subvector of a vector
# We define a vector for the following examples
A=c(15, 20,35, 0:8)
A
# Extracting only one element, e.g. the second
A[2]
# Extracting several elements: Give a vector with the position number in
# []-brackets. E.g. to extract the 2nd to 4th argument, write
A[2:4]
# Give a Boolean vector (of same length as A) as argument in []-brackets.
# Only those elements of A, for which the Boolean vector is TRUE will be
# extracted. Example: Since A has length 12, the Boolean vector must have
# length 12 as well. We define a vector S, which has TRUE on the 1st, 4th,
# 7th and 10th place and FALSE on the other places. Thus the 1st, 4th,
# 7th and 10th element of S are extracted.
S=rep(c(TRUE, FALSE,FALSE), 4)
S
A[S]
# This methods can not only be used to read the vector, but also to modify it.
# Assigning to one element of the vector a new value.
A[2]=5
A
# Assigning to several arguments of a vector the same (new) value.
A[6:9]=-1
A
# Assigning to various elements of a vector various values (at one time).
A[S]=c(60,63, 65, 66)
A
### Vector Operation
# When a function is applied to a vector, R returns a vector of the function
# applied to all arguments.
# So, if you want to have a vector consisting of all square roots from arguments
# of A, a vector, in which every element of A is increasing by 1, or a Boolean
# vector, which is TRUE exactly at those positions, where A is -1, then write:
sqrt(A)
A+1
A==-1
# You can also let R sort a vector or give a vector with the rank the elements
# have within the whole sample.
sort(A)
rank(A)
### Data Frames
### Defining Data Frames
# A data frame to a collection of several vectors of the same length.
# Defining a data frame by hand
x=data.frame(Year=2010:2013, Day.Temperature=c(21,19, 23,22),
Night.Temperature=c(9,10,10,9))
x
# Reading in data from a file
y <- read.table("widerstand.txt", col.names = c("radius", "R"))
### Before you have to tell R, in which directory the data is, by clicking
### File - Change directory in the menu
y
### Vectors and data
# The second argument of the second vector
x[2,2]
# The second argument of all vectors
x[2,]
# The second vector
x[,2]
# The vector called "Day.Temperature" (another way of accessing the second
# vector)
x$Day.Temperature
### Exercise
# We want a vector of all year, in which the day temperature is larger than 20.
# Solution see other script.