



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




The user interface of R studio can be found in Figure 1. The main elements are:
Editor (1). Edit program files (and other files such as Rmarkdown) here. To change the font size, use Tools/Global Options/Appearance
Console (2). Run single commands here directly. Results will also be displayed here.
Environment (3). A view into the “memory” of R – all currently defined variables. Clean the environment with the command rm(list=ls()) or by clicking on the brush (3a).
History (4). List of recently used commands. Useful for experimenting.
Packages (5). List of all installed (empty checkbox) and loaded (checked box) packages.
Contents of working directory (6). R expects to find input data in this directory and saves output files here. Change the working directory using the menu item Session/Set Working Directory/... or the command setwd().
Plots (7). Here, all plots will be displayed.
1
2
3
4
5
6 7
8 3a
Figure 1: R Studio. (1) Editor, (2) Console, (3) Environment, (3a) ”Clear environment” button, (4) History, (5) Packages, (6) Contents of the working directory, (7) Display of plots
Variables. Variables are created implicitly, i.e. by assigning a value to them. The command x<-1 performs two things: (1) a variable called x is created, and (2) the value 1 is assigned to it. Variables can be of different types: numeric, factors and string (for text). All types can be organized in the form of scalars, vectors, matrices and dataframes. Note that the names of variables are case sensitive (so A is not the same as a). Variables should be named with self-explaining names. Variables live until R is shut down or until they are explicitly cleared. Use rm("x") to clear variable x and rm(list=ls()) to clear all variables.
Arithmetic operators. An operator is best explained with an example: +, −, ∗, / are all arith- metic operators. The hat ^ stands for the power operator, e.g. 5^2 is written as 5^2. (Remember that √ nx = x 1 /n). The order in which operators are executed is called operator precedence. Example:
2+3*5. The multiplication is executed before the sum..
Relational operators. So-called relational operators compare two variables and give the results TRUE or FALSE. Among these are: equal (==), not equal (!=), less (<), less or equal (<=), greater (>), greater or equal (>=). Relations can only be true or false. R assigns numerical values to these two: TRUE=1 and FALSE=0. Example: 2<3 is TRUE (or 1 ), 4.4==4.5 is FALSE (or 0 ).
Logical operators. Most noteworthy are “and”(&), “or” (|) and not (!). They are used to combine two conditions. Example: (2<3) | (4.4==4.5) is TRUE, because one of the two operands is true.
Functions. An R function works like a standard mathematical function: it takes one or more arguments and produces one or several results. Widely used built-in functions are log(), exp(), abs(), sqrt(). R extends the concept of a function to vectors. Example: given a vector x = (x 1 , x 2 , x 3 ), R computes log(x) = (log(x 1 ), log(x 2 ), log(x 3 )). Apart from these built-in functions, users have the flexibility to write user-defined functions. Note that these work only as well as they have been programmed. User-defined functions are only vector compatible, if the user has explicitly provided for this. Generally, a user-defined function must be saved in a separate m-file.
Flow control. Many computational algorithms require repeating certain steps, often as a func- tion of previous results. In R, a block of code can be executed several times (using for, while) or subject to a condition (using if). Blocks of code start with { and end with }.
Comments. R ignores all text after a hash sign (#) until the end of the line. Start a line with
important element of programming style.
Data input and output. It is not customary to let the user interactively input data. Small amounts of data such as parameter choices are often specified in the first block of a program. Larger amounts of data are usually stored in a separate data file. R can directly access many database systems and read and write various file formats, including CSV and MS Excel. Several packages allow accessing online databases. The results of a calculation can be written on the screen using print() or – if some formatting is required – sprint().
x+y Arithmetic operators are + - / * and ^ for “power”. x-y Negative numbers are simply entered with a minus in front. z <- x+y Assign the result of a calculation to a new variable. x+yz Operator precedence (x+y)z Round brackets have the highest precedence. NOTE: every shape of brackets has its own meaning. ((x+y)*z+x)/x Several levels of brackets are all defined with the round bracket (). x^y Power. x^y+z This may produce an undesired result... x^(y+z) If you want to enter xy+z^ , you have to use a bracket. x^2 Squared sqrt(x) Square root. But is there also a command for the third root of x? x^(1/3) There is none. We need to use our mathematics knowledge: 3
x = x^1 /^3. x^0.33 Compare the results. Never perform computations for the computer!
options(digits=16) Display output with full 16 digit precision. The maximum number of digits that can be shown is 22. Hitting the key gives the last input. Hit is twice and get x^0.33. options(digits=6) NOTE: digits only changes the display – not the result of the calculation.
log(x) Natural logarithm (some people write ln() for it) ... log10(x) ... as opposed to the logarithm with basis 10. exp(x) Exponential. abs(-3) Absolute value. runif(1) runif() stands for ramdom draw from them uniform distribution. Try several times. Use. Compare to your neighbour.
log(0) A pocket calculator would give an error, here. myError <- 0/0 Another error. NaN stands for not a number. 1+myError Calculations with NaN are possible, but most of the time not very useful.
xVec <- c(1, 3, 7) This creates a row vector: commas separate the columns of a vector. yVec <- c(2, 5, 1) The commas are not needed: use spaces as shortcut. xVec*yVec Element-by-element multiplication. xVec[1] Obtain a specific element of a vector. xVec[1] <- 9 Change a specific elements of a vector. xVec[2] <- 0 Set one element of zero. This is not the same as ... xVec <- xVec[-2] deleting one element of the vector. Compare the result to the line above. xVec <- c(xVec, 8) Add an entry at the end of the vector. Can be done several times using [cursor up]
Z <- matrix(c(5,7,2,4), nrow=2) creates a 2 × 2 matrix Z <- matrix(c(5,7,2,4), nrow=2, byrow= TRUE) more natural way to enter a matrix Z[1,2] Before hitting return, predict the result. Remember: row, column ZxVec If the dimensions do not match you get an error message. Zc(1,2) This works, but the result is a bit unexpected. diag(2) Identity matrix. Zdiag(2) Unexpected result. Z%%diag(2) Use %*% for matrix multiplication.
1:5 The colon operator produces a vector in steps of 1. seq(1,5, 0w.5) Equally spaced vector with increments different than 1. xVec[1:2] Main use of the colon operator: to access a range of elements. xVec[c(1,2)] These two things are the same. xVec[c(3,1,2)] We can even change the order of elements.
aCol <- c(3,4,5,6) Create two vectors for the next commands. bCol <- c(4,3,2,1) uMx <- cbind(aCol, bCol) Create a matrix by concatenating column vectors. vMx <- cbind(uMx,aCol) We can even concatenate matrices and vectors. uMx <- rbind(aCol, bCol) Create a matrix by concatenating row vectors. stk1 <- rnorm(100) Create some random stock return data. stk2 <- rnorm(100) stk3 <- rnorm(100) stock <- cbind(stk1,stk2,stk3) Matrix of stock returns. dim(stock) Obtain the dimensions of our data set: number of rows, columns. stock[,1] First column only, i.e. the returns for stock number 1. stock[2,] Second row only, i.e. the returns of all stocks on day 2. stock[,1:2] Subset of stocks number 1 to 3. stock[,c(1,3)] Subset of stocks number 1 and 3 only.
0==1 NOTE: Double equality sign for comparisons. In R, FALSE=... 1<2... and TRUE=1. This can be used for calculations: 17 * (0==1) Remember, that 0==1 is FALSE and hence 0. yVec