Torfs+Brauer Short R Intro

Transcript

1 http://www.r-project.org/ A (very) short and do the following (assuming you work on a introduction to R windows computer): • in the left bar download CRAN click choose a download site • Paul Torfs & Claudia Brauer Windows choose • as target operation system Hydrology and Quantitative Water Management Group • click base † Download R 3.0.3 for Windows choose • and Wageningen University, The Netherlands choose default answers for all questions 3 March 2014 It is also possible to run R and RStudio from a USB stick instead of installing them. This could be useful when you don’t have administra- 1 Introduction tor rights on your computer. See our separate note “How to use portable versions of R and RStudio” R is a powerful language and environment for sta- for help on this topic. tistical computing and graphics. It is a public do- main (a so called “GNU”) project which is similar 2.2 Install RStudio to the commercial S language and environment which was developed at Bell Laboratories (for- After finishing this setup, you should see an ”R” merly AT&T, now Lucent Technologies) by John icon on you desktop. Clicking on this would start Chambers and colleagues. R can be considered as up the standard interface. We recommend, how- ‡ a different implementation of S, and is much used ever, to use the RStudio interface. To install in as an educational language and research tool. RStudio, go to: The main advantages of R are the fact that R http://www.rstudio.org/ is freeware and that there is a lot of help available online. It is quite similar to other programming and do the following (assuming you work on a win- packages such as MatLab (not freeware), but more dows computer): user-friendly than programming languages such as Download RStudio • click C++ or Fortran. You can use R as it is, but for Download RStudio Desktop click • educational purposes we prefer to use R in combi- Recommended For Your System click • nation with the RStudio interface (also freeware), .exe • file and run it (choose default download the which has an organized layout and several extra answers for all questions) options. This document contains explanations, exam- 2.3 RStudio layout ples and exercises, which can also be understood The RStudio interface consists of several windows (hopefully) by people without any programming (see Figure 1). experience. Going through all text and exercises takes about 1 or 2 hours. Examples of frequently console window Bottom left: • (also called used commands and error messages are listed on ). Here you can type command window the last two pages of this document and can be ” prompt and > simple commands after the “ used as a reference while programming. R will then execute your command. This is the most important window, because this is where R actually does stuff. 2 Getting started (also called editor window Top left: • script 2.1 Install R window ). Collections of commands (scripts) To install R on your computer (legally for free!), can be edited and saved. When you don’t get ∗ : go to the home website of R † At the moment of writing 3.0.3 was the latest version. ∗ Choose the most recent one. On the R-website you can also find this docu- ‡ There are many other (freeware) interfaces, such as Tinn- ment: http://cran.r-project.org/doc/contrib/Torfs+ R. Brauer-Short-R-Intro.pdf 1

2 Figure 1 The editor, workspace, console and plots windows in RStudio. you ask R to open a certain file, it will look in the File → this window, you can open it with working directory for this file, and when you tell R script → New R to save a data file or figure, it will save it in the Just typing a command in the editor window working directory. is not enough, it has to get into the command window before R executes the command. If Before you start working, please set your work- you want to run a line from the script window ing directory to where all your data and script files (or the whole script), you can click or Run are or should be stored. CTRL+ENTER press to send it to the command window: command the in Type window. . For example: setwd("directoryname") • Top right: workspace / history window . > setwd("M:/Hydrology/R/") In the workspace window you can see which data and values R has in its memory. You Make sure that the slashes are forward slashes and can view and edit the values by clicking on that you don’t forget the apostrophes (for the rea- them. The history window shows what has son of the apostrophes, see section 10.1). R is case been typed before. sensitive, so make sure you write capitals where necessary. Bottom right: • files / plots / packages / Within RStudio you can also go to Tools / Set . Here you can open files, view help window . working directory plots (also previous plots), install and load packages or use the help function. 2.5 Libraries You can change the size of the windows by drag- R can do many statistical and data analyses. They ging the grey bars between the windows. are organized in so-called packages or libraries . With the standard installation, most common 2.4 Working directory packages are installed. Your working directory is the folder on your com- To get a list of all installed packages, go to the puter in which you are currently working. When packages window or type library() in the console 2

3 window. If the box in front of the package name is You can see that a appears in the workspace win- dow, which means that R now remembers what ticked, the package is loaded (activated) and can § is (just type a You can also ask R what be used. is. a a ENTER There are many more packages available on the in the command window): R website. If you want to install and use a pack- > a age (for example, the package called “geometry”) [1] 4 you should: install packages Install the package: click • a or do calculations with : in the packages window and type geometry > a * 5 or type install.packages("geometry") in the [1] 20 command window. check box in front of Load the package: • If you specify again, it will forget what value a or type in the library("geometry") geometry it had before. You can also assign a new value to command window. using the old one. a > a = a + 10 3 Some first examples of R > a [1] 14 commands To remove all variables from R’s memory, type 3.1 Calculator > rm(list=ls()) R can be used as a calculator. You can just type your equation in the command window after the or click “clear all” in the workspace window. You ”: > “ can see that RStudio then empties the workspace window. If you only want to remove the variable > 10^2 + 36 , you can type a rm(a) . and R will give the answer ToDo Repeat the previous ToDo, but with several [1] 136 steps in between. You can give the variables ToDo any name you want, but the name has to start Compute the difference between 2014 and the with a letter. year you started at this university and divide this by the difference between 2014 and the year you were born. Multiply this with 100 to get 3.3 Scalars, vectors and matrices the percentage of your life you have spent at this university. Use brackets if you need them. Like in many other programs, R organizes num- bers in scalars (a single number – 0-dimensional), vectors (a row of numbers, also called arrays – matrices 1-dimensional) and (like a table – 2- If you use brackets and forget to add the closing dimensional). bracket, the “ ” on the command line changes > a The you defined before was a scalar. To define into a “+”. The “+” can also mean that R is still a vector with the numbers 3, 4 and 5, you need the busy with some heavy computation. If you want ¶ , which is short for concatenate (paste c function R to quit what it was doing and give back the “ > ”, together). ESC (see the reference list on the last page). press b=c(3,4,5) 3.2 Workspace Matrices and other 2-dimensional structures You can also give numbers a name. By doing so, will be introduced in Section 6. they become so-called variables which can be used § = instead of Some people prefer te use (they do the <- later. For example, you can type in the command and same thing). <- consists of two characters, < - , and represents an arrow pointing at the object receiving the window: value of the expression. > a = 4 ¶ See next Section for the explanation of functions. 3

4 3.4 Functions > rnorm(10, mean=1.2, sd=3.4) If you would like to compute the mean of all the b from the example above, elements in the vector showing that the same function ( rnorm ) may have you could type different interfaces and that R has so called named mean ). By the way, (in this case arguments sd and > (3+4+5)/3 the spaces around the “,” and “=” do not matter. But when the vector is very long, this is very bor- Comparing this example to the previous one ing and time-consuming work. This is why things also shows that for the function rnorm only the you do often are automated in so-called . functions first argument (the number 10) is compulsory, and Some functions are standard in R or in one of the that R gives default values to the other so-called ‖ packages. You can also program your own func- optional arguments. tions (Section 11.3). When you use a function to RStudio has a nice feature: when you type compute a mean, you’ll type: , rnorm( in the command window and press TAB RStudio will show the possible arguments (Fig. 2). > mean(x=b) Within the brackets you specify the . arguments 3.5 Plots Arguments give extra information to the function. R can make graphs. The following is a very sim- x says of which set In this case, the argument ∗∗ ple example: of numbers (vector) the mean should computed ). Sometimes, the name of the argu- (namely of b > x = rnorm(100) 1 ment is not necessary: works as well. mean(b) > plot(x) 2 ToDo • In the first line, 100 random numbers are Compute the sum of 4, 5, 8 and 11 by first com- , which becomes a assigned to the variable x bining them into a vector and then using the vector by this operation. sum function . In the second line, all these values are plotted • in the plots window. , as another example, is a rnorm The function standard R function which creates random sam- ToDo ples from a normal distribution. Hit the ENTER Plot 100 normal random numbers. key and you will see 10 random numbers as: 1 > rnorm(10) 2 [1] -0.949 1.342 -0.474 0.403 4 Help and documentation 3 [5] -0.091 -0.379 1.015 0.740 4 [9] -0.639 0.950 There is a large amount of (free) documentation and help available. Some help is automatically • Line 1 contains the command: rnorm is the func- installed. Typing in the console window the com- tion and the 10 is an argument specifying how mand many random numbers you want — in this case > help(rnorm) 10 instead of just n=10 10 numbers (typing would also work). • Lines 2-4 contain the results: 10 random num- function. It gives a de- rnorm gives help on the bers organised in a vector with length 10. scription of the function, possible arguments and Entering the same command again produces 10 the values that are used as default for optional new random numbers. Instead of typing the same arguments. Typing text again, you can also press the upward arrow > example(rnorm) key ( ↑ ) to access previous commands. If you want 10 random numbers out of normal distribution ‖ Use the help function (Sect. 4) to see which values are with mean 1.2 and standard deviation 3.4 you can used as default. ∗∗ See Section 7 for slightly less trivial examples. type 4

5 Figure 2 TAB after the function name and bracket. RStudio shows possible arguments when you press gives some examples of how the function can be You can store your commands in files, the so- used. . These scripts have typically file scripts called names with the extension . You can foo.R , e.g. .R An HTML-based global help can be called with: open an editor window to edit these files by click- > help.start() †† New ing File and or . Open file... You can run (send to the console window) or by going to the help window. part of the code by selecting lines and pressing The following links can also be very useful: CTRL+ENTER or click Run in the editor window. If http://cran.r-project.org/doc/manuals/ • you do not select anything, R will run the line R-intro.pdf A full manual. your cursor is on. You can always run the whole http://cran.r-project.org/doc/contrib/ • script with the console command source , so e.g. Short-refcard.pdf A short reference card. foo.R you type: for the script in the file • http://zoonek2.free.fr/UNIX/48_R/all. html > source("foo.R") A very rich source of examples. • http://rwiki.sciviews.org/doku.php in the editor window You can also click Run all A typical user wiki. CTRL+SHIFT + S or type to run the whole script • http://www.statmethods.net/ at once. Also called Quick-R. Gives very productive ToDo direct help. Also for users coming from other programming languages. containing R- firstscript.R Make a file called http://mathesaurus.sourceforge.net/ • code that generates 100 random numbers and Dictionary for programming languages (e.g. R for plots them, and run this script several times. Matlab users). Just using Google (type e.g. “R rnorm” in the • search field) can also be very productive. 6 Data structures ToDo If you are unfamiliar with R, it makes sense to just function. sqrt Find help for the retype the commands listed in this section. Maybe you will not need all these structures in the begin- ning, but it is always good to have at least a first glimpse of the terminology and possible applica- 5 Scripts tions. R is an interpreter that uses a command line based 6.1 Vectors environment. This means that you have to type commands, rather than use the mouse and menus. were already introduced, but they can do Vectors This has the advantage that you do not always more: have to retype all commands and are less likely to †† Where also the options Save and Save as are available. get complaints of arms, neck and shoulders. 5

6 ToDo > vec1 = c(1,4,6,8,10) 1 Put the numbers 31 to 60 in a vector named > vec1 2 and in a matrix with 6 rows and 5 columns P [1] 1 4 6 8 10 3 . Tip: use the function named Q . Look at seq 4 > vec1[5] the different ways scalars, vectors and matrices 5 [1] 10 are denoted in the workspace window. > vec1[3] = 12 6 > vec1 7 [1] 1 4 12 8 10 8 Matrix-operations are similar to vector opera- > vec2 = seq(from=0, to=1, by=0.25) 9 tions: 10 > vec2 1 > mat[1,2] [1] 0.00 0.25 0.50 0.75 1.00 11 2 [1] 3 12 > sum(vec1) 3 > mat[2,] [1] 35 13 4 [1] 2 4 6 14 > vec1 + vec2 5 > mean(mat) [1] 1.00 4.25 12.50 8.75 11.00 15 [1] 4.8333 6 Elements of a matrix can be addressed in the • • In line 1, a vector vec1 is explicitly constructed (line 1). usual way: [row,column] by the concatenation function c() , which was in- Line 3: When you want to select a whole row, • troduced before. Elements in vectors can be ad- you leave the spot for the column number empty dressed by standard [i] indexing, as shown in (the other way around for columns of course). lines 4-5. Line 5 shows that many functions also work • • In line 6, one of the elements is replaced with a with matrices as argument. new number. The result is shown in line 8. Line 9 demonstrates another useful way of con- • (sequence) function. structing a vector: the seq() • Lines 10-15 show some typical vector oriented 6.3 Data frames calculations. If you add up two vectors of the Time series are often ordered in . A data frames same length, the first elements of both vectors are data frame is a matrix with names above the summed, and the second elements, etc., leading to columns. This is nice, because you can call and a new vector of length 5 (just like in regular vector use one of the columns without knowing in which sums up the calculus). Note that the function sum position it is. elements within a vector, leading to one number (a scalar). > t = data.frame(x = c(11,12,14), 1 y = c(19,20,21), z = c(10,9,7)) 2 > t 3 6.2 Matrices x y z 4 1 11 19 10 5 are nothing more than 2-dimensional Matrices 2 12 20 9 6 To define a matrix, use the function vectors. 7 3 14 21 7 matrix : > mean(t$z) 8 [1] 8.666667 9 mat=matrix(data=c(9,2,3,4,5,6),ncol=3) 1 > mean(t[["z"]]) 10 > mat 2 [1] 8.666667 11 3 [,1] [,2] [,3] [1,] 9 3 5 4 • t In lines 1-2 a typical data frame called is 5 [2,] 2 4 6 y , constructed. The columns have the names x and z . specifies which numbers The argument data • Line 8-11 show two ways of how you can select to spec- should be in the matrix. Use either ncol from the data frame called t . the column called z to specify the ify the number of columns or nrow number of rows. 6

7 ToDo Hundred random numbers are plotted by connect- Make a script file which constructs three ran- ing the points by lines (the symbol between quotes dom normal vectors of length 100. Call these after the type= , is the letter l, not the number 1) , x2 and x3 . Make a data frame called vectors x1 in a gold color. , t with three columns (called a ) con- b and c Another very simple example is the classical sta- taining respectively . , x1+x2 x1 and x1+x2+x3 tistical histogram plot, generated by the simple Call the following functions for this data frame: command plot(t) and . Can you understand the sd(t) > hist(rnorm(100)) results? Rerun this script a few times. which generates the plot in Figure 3. 6.4 Lists Histogram of rnorm(100) list . The main Another basic structure in R is a advantage of lists is that the “columns” (they’re 20 not really ordered in columns any more, but are 15 more a collection of vectors) don’t have to be of the same length, unlike matrices and data frames. 10 Frequency 1 > L = list(one=1, two=c(1,2), 5 five=seq(0, 1, length=5)) 2 0 > L 3 0 −1 1 −2 −3 2 $one 4 rnorm(100) 5 [1] 1 6 $two A simple histogram plot. Figure 3 7 [1] 1 2 8 $five [1] 0.00 0.25 0.50 0.75 1.00 9 The following few lines create a plot using the data 10 > names(L) frame constructed in the previous ToDo: t 11 [1] "one" "two" "five" 12 > L$five + 10 plot(t$a, type="l", ylim=range(t), 1 13 [1] 10.00 10.25 10.50 10.75 11.00 2 lwd=3, col=rgb(1,0,0,0.3)) lines(t$b, type="s", lwd=2, 3 4 col=rgb(0.3,0.4,0.3,0.9)) Lines 1-2 construct a list by giving names and • points(t$c, pch=20, cex=4, 5 values. The list also appears in the workspace 6 col=rgb(0,0,1,0.3)) window. Lines 3-9 show a typical printing (after pressing • ). L ENTER ToDo Line 10 illustrates how to find out what’s in the • Add these lines to the script file of the previous list. section. Try to find out, either by experiment- • Line 12 shows how to use the numbers. ing or by using the help, what the meaning is of , . , pch cex rgb , the last argument of rgb , lwd 7 Graphics To learn more about formatting plots, search Plotting is an important statistical activity. So it for par in the R help. Google “R color chart” for should not come as a surprise that R has many a pdf file with a wealth of color options. plotting facilities. The following lines show a sim- ple plot: To copy your plot to a document, go to the plots window, click the “Export” button, choose the > plot(rnorm(100), type="l", col="gold") nicest width and height and click Copy or Save . 7

8 8 Reading and writing data files There are many ways to write data from within the R environment to files, and to read data from files. We will illustrate one way here. The following lines illustrate the essential: of section 8 (left) tst0.txt The files Figure 4 1 > d = data.frame(a = c(3,4,5), tst1.txt and from the ToDo below (right) 2 b = c(12,43,54)) opened in two text editors. 3 > d a b 4 1 3 12 5 9 Not available data 2 4 43 6 ToDo 3 5 54 7 Compute the mean of the square root of a vec- > write.table(d, file="tst0.txt", 8 tor of 100 random numbers. What happens? row.names=FALSE) 9 > d2 = read.table(file="tst0.txt", 10 11 header=TRUE) > d2 12 When you work with real data, you will en- a b 13 counter missing values because instrumentation 1 3 12 14 failed or because you didn’t want to measure in 2 4 43 15 the weekend. When a data point is , not available 16 3 5 54 instead of a number. NA you write > j = c(1,2,NA) In lines 1-2, a simple example data frame is • . d constructed and stored in the variable • Lines 3-7 show the content of this data frame: Computing statistics of incomplete data sets two columns (called a and b ), each containing Maybe the is strictly speaking not possible. three numbers. largest value occurred during the weekend when • Line 8 writes this data frame to a text file, you didn’t measure. Therefore, R will say that it called tst0.txt The argument row.names=FALSE j doesn’t know what the largest value of is: prevents that row names are written to the file. > max(j) , col.names Because nothing is specified about [1] NA the default option is chosen and col.names=TRUE column names are written to the file. Figure 4 shows the resulting file (opened in an editor, such If you don’t mind about the missing data and b ) in as Notepad), with the column names ( a and want to compute the statistics anyway, you can the first line. (Should I remove na.rm=TRUE add the argument Lines 10-11 illustrate how to read a file into • the NAs? Yes!). a data frame. Note that the column names are also read. The data frame also appears in the > max(j, na.rm=TRUE) workspace window. [1] 2 ToDo 10 Classes Make a file called in Notepad from tst1.txt The exercises you did before were nearly all with the example in Figure 4 and store it in your numbers. Sometimes you want to specify some- working directory. Write a script to read it, to thing which is not a number, for example the name by 5 and to store g multiply the column called of a measurement station or data file. In that case . tst2.txt it as you want the variable to be a character string in- stead of a number. 8

9 ToDo An object in R can have several so-called Make a graph with on the x-axis: today, Sin- numeric , . The most important three are classes terklaas 2014 and your next birthday and on character and (date-time combinations). POSIX the y-axis the number of presents you expect on You can ask R what class a certain variable is by each of these days. Tip: make two vectors first. . class(...) typing 10.1 Characters To tell R that something is a character string, you 11 Programming tools should type the text between apostrophes, other- wise R will start looking for a defined variable with When you are building a larger program than in the same name: the examples above or if you’re using someone else’s scripts, you may encounter some program- > m = "apples" ming statements. In this Section we describe a > m few tips and tricks. [1] "apples" > n = pears 11.1 If-statement Error: object ‘pears’ not found The if-statement is used when certain computa- Of course, you cannot do computations with be done when a certain condi- only tions should character strings: tion is met (and maybe something else should be done when the condition is not met). An example: > m + 2 Error in m + 2 : non-numeric argument to 1 > w = 3 binary operator 2 > if( w < 5 ) 3 { 10.2 Dates d=2 4 }else{ 5 Dates and times are complicated. R has to know d=10 6 that 3 o’clock comes after 2:59 and that February 7 } has 29 days in some years. The easiest way to tell > d 8 R that something is a date-time combination is 9 2 strptime : with the function > date1=strptime( c("20100225230000", 1 should be w In line 2 a condition is specified: • "20100226000000", "20100226010000"), 2 less than 5. format="%Y%m%d%H%M%S") 3 If the condition is met, R will execute what is • > date1 4 between the first brackets in line 4. [1] "2010-02-25 23:00:00" 5 If the condition is not • met, R will execute what [2] "2010-02-26 00:00:00" 6 in is between the second brackets, after the else 7 [3] "2010-02-26 01:00:00" -part out if line 6. You can leave the else{...} you don’t need it. • has been In this case, the condition is met and d . • In lines 1-2 you create a vector with c(...) assigned the value 2 (lines 8-9). The numbers in the vectors are between apostro- To get a subset of points in a vector for which needs char- phes because the function strptime a certain condition holds, you can use a shorter acter strings as input. method: In line 3 the argument • format specifies how the character string should be read. In this case the > a = c(1,2,3,4) 1 year is denoted first (%Y), then the month (%m), > b = c(5,6,7,8) 2 day (%d), hour (%H), minute (%M) and second 3 > f = a[b==5 | b==8] (%S). You don’t have to specify all of them, as 4 > f long as the format corresponds to the character 5 [1] 1 4 string. 9

10 • In line 1 and 2 two vectors are made. 11.3 Writing your own functions In line 3 you say that is composed of those f • Functions you program yourself work in the same equals 5 or b b elements of vector for which a way as pre-programmed R functions. equals 8. 1 > fun1 = function(arg1, arg2 ) = Note the double in the condition. Other con- 2 { ditions (also called logical or Boolean operators) 3 w = arg1 ^ 2 ) and >= ( ≥ ). To test more are < , > , != ( 6 =), <= ( ≤ 4 return(arg2 + w) & than one condition in one if-statement, use if } 5 both conditions have to be met (“and”) and | if 6 > fun1(arg1 = 3, arg2 = 5) one of the conditions has to be met (“or”). [1] 14 7 8 11.2 For-loop ) and its argu- In line 1 the function name ( • fun1 If you want to model a time series, you usually do and arg2 ) are defined. arg1 ments ( the computations for one time step and then for • Lines 2-5 specify what the function should do if the next and the next, etc. Because nobody wants ) is shown arg2+w it is called. The return value ( to type the same commands over and over again, on the screen. these computations are automated in for-loops. • In line 6 the function is called with arguments 3 In a you specify what has to be done for-loop and 5. and how many times. To tell “how many times”, you specify a so-called counter. An example: ToDo > h = seq(from=1, to=8) 1 Write a function for the previous ToDo, so 2 > s = c() that you can feed it any vector you like > for(i in 2:10) 3 Use a for-loop in the func- (as argument). 4 { tion to do the computation with each ele- 5 s[i] = h[i] * 10 ment. Use the standard R function length a } 6 in the specification of the counter. ) > s 7 [1] NA 20 30 40 50 60 70 80 NA NA 8 a Actually, people often use more for-loops than nec- essary. The ToDo above can be done more easily is made. h • First the vector and quickly without a for-loop but with regular vector- computations. In line 2 an empty vector ( s ) is created. This is • necessary because when you introduce a variable within the for-loop, R will not remember it when it has gotten out of the for-loop. • In line 3 the for-loop starts. In this case, i is the counter and runs from 2 to 10. • Everything between the curly brackets (line 5) is processed 9 times. The first time i=2 , the second element of h is multiplied with 10 and placed in the second position of the vector s . The second th , etc. In the last two runs, the 9 and i=3 time th are requested, which do not elements of h 10 exist. Note that these statements are evaluated without any explicit error messages. ToDo Make a vector from 1 to 100. Make a for-loop which runs through the whole vector. Multiply the elements which are smaller than 5 and larger than 90 with 10 and the other elements with 0.1. 10

11 12 Some useful references : largest or smallest element min or max • rowMeans (or rowSums • colMeans ): and colSums , sums (or means) of all numbers in each row (or 12.1 Functions column) of a matrix. The result is a vector. This is a subset of the functions explained in the • quantile(x,c(0.1,0.5)) : sample the 0.1 and th R reference card. x quantiles of vector 0.5 Data creation Data processing • read.table : read a table from file. Arguments: : create a vector with equal steps between • seq header=TRUE : read first line as titles of the the numbers : numbers are separated by sep="," columns; rnorm • : create a vector with random numbers n lines. : don’t read the first commas; skip=n with normal distribution (other distributions are • write.table : write a table to file also available) • : paste numbers together to create a vector c • sort : sort elements in increasing order : length • array : create a vector, Arguments: dim • t : transpose a matrix ncol : create a matrix, Arguments: matrix • split : aggregate(x,by=ls(y),FUN="mean") • : number of rows/columns nrow and/or ) and com- y into subsets (defined by x data set • data.frame : create a data frame putes means of the subsets. Result: a new list. • : create a list list package). Ar- zoo : interpolate (in na.approx • • cbind combine vectors into a and rbind : s. Result: vector without NA gument: vector with matrix by row or column s. NA cumsum : cumulative sum. Result is a vector. • Extracting data : moving average (in the package) zoo rollmean • th element of a vector n • : the x[n] • : paste character strings together paste th th : the n to element m x[m:n] • • substr : extract part of a character string • x[c(k,m,n)] : specific elements m : elements between x[x>m & x

12 paste x curve(x^2) in the expression. Example: • ALT+TAB : change to another program window • : add legend with given symbols ( lty legend ↓ • ↑ , → or ← , : move cursor ) at location legend or pch and col ) and text ( • or END : move cursor to begin or end of line HOME ( ) x="topright" • Page Up or Page Down : move cursor one page 1 – side : add axis. Arguments: • axis =bottom, up or down 2 =left, 3 =top, 4 =right SHIFT+ • : select /HOME/END/PgUp/PgDn → / ← / ↓ / ↑ text mtext • : add text on axis. Arguments: (character string) and side grid • : add grid • par : plotting parameters to be specified before 12.3 Error messages : the plots. mfrow=c(1,3)) Arguments: e.g. Cannot • No such file or directory or number of figures per page (1 row, 3 columns); change working directory new=TRUE : draw plot over previous plot. Make sure the working directory and file names are correct. Plotting parameters • Object ‘x’ not found , lines , plot These can be added as arguments to x has not been defined yet. Define The variable . , etc. For help see image par x or write apostrophes if x should be a character =points, etc. "p" =lines, : type • "l" string. "red" , etc • col : color – "blue" , • Argument ‘x’ is missing without default =dashed, etc. 2 =solid, 1 lty • : line type – x You didn’t specify the compulsory argument . =triangle, etc. 1 2 pch • =circle, : point type – + • main : title - character string • R is still busy with something or you forgot • : axis labels – character string ylab and xlab . closing brackets. Wait, type ) or press ESC or } • xlim and ylim : range of axes – e.g. c(1,10) Unexpected ’}’ or Unexpected ’)’ in ")" • • log : logarithmic axis – "x" , or "xy" "y" in "}" The opposite of the previous. You try to close Programming something which hasn’t been opened yet. Add function defini- : function(arglist){expr} • opening brackets. tion: do with list of arguments expr arglist • Unexpected ‘else’ in "else" if(cond){expr1}else{expr2} : if-statement: • else Put the of an if-statement on the same line expr2 , else expr1 cond if is true, then . }else{ as the last bracket of the “then”-part: for(var in vec) {expr} • : for-loop: the • Missing value where TRUE/FALSE needed and does counter var runs through the vector vec Something goes wrong in the condition-part expr each run if(x==1) ) of an if-statement. Is x NA ? ( • while(cond){expr} is cond : while-loop: while The condition has length > 1 and only • each run expr true, do the first element will be used In the condition-part ( if(x==1) ) of an if- statement, a vector is compared with a scalar. Is 12.2 Keyboard shortcuts a vector? Did you mean x ? x[i] • Non-numeric argument to binary operator There are several useful keyboard shortcuts for You are trying to do computations with something RStudio (see Help → Keyboard Shortcuts ): class(...) to find which is not a number. Use CRL+ENTER • : send commands from script window as.numeric(...) out what went wrong or use to to command window transform the variable to a number. in command window: previous or next ↓ or • ↑ or Argument is of length zero • Replacement command is of length zero CTRL+1 , • CTRL+2 , etc.: change between the The variable in question is NULL , which means windows that it is empty, for example created by c() . Check the definition of the variable. Not R-specific, but very useful keyboard short- cuts: CTRL+V , CTRL+C • : copy, cut and and CTRL+X 12

Related documents

F:\MySites\InterLand\Math\Cours

F:\MySites\InterLand\Math\Cours

CLASS FIELD THEORY J.S. Milne

More info »
Evaluating the link between the sulfur rich Laacher See volcanic eruption and the Younger Dryas climate anomaly

Evaluating the link between the sulfur rich Laacher See volcanic eruption and the Younger Dryas climate anomaly

Clim. Past, 14, 969–990, 2018 https://doi.org/10.5194/cp-14-969-2018 © Author(s) 2018. This work is distributed under the Creative Commons Attribution 4.0 License. Evaluating the link between the sulf...

More info »
e infty

e infty

'Edited by Dold and B. Eckmann A J. May Peter - E, Ring Spaces and E, Ring Spectra with contributions by Frank Quinn, Nigel Ray, Tornehave Jnrrgen and Springer-Verlag Berlin Heidelberg New York

More info »
10 3 Article 2 Ludic Lover

10 3 Article 2 Ludic Lover

Beyond the Ludic Lover Individual Differences in Playfulness and Love Styles in Heterosexual Relationships • René T. Proyer, Kay Brauer, Annegret Wolf, and Garry Chick Adult playfulness contributes to...

More info »
000 final 3264

000 final 3264

3264 & All That Intersection Theory in Algebraic Geometry c David Eisenbud and Joe Harris

More info »
CalCOFI Atlas 33

CalCOFI Atlas 33

THE EARLY STAGES IN OF THE FISHES CALIFORNIA CURRENT REGION CALIFORNIA FISHERIES COOPERATIVE OCEANIC INVESTIGATIONS ATLAS NO. 33 BY THE SPONSORED STATES OF COMMERCE DEPARTMENT UNITED OCEANIC AND ATMOS...

More info »
soga 2019 report

soga 2019 report

STATE OF /2019 GLOBAL AIR A SPECIAL REPORT ON GLOBAL EXPOSURE TO AIR POLLUTION AND ITS DISEASE BURDEN The State of Global Air is a collaboration between the Health Effects Institute and the Institute ...

More info »
CityNT2019TentRoll 1

CityNT2019TentRoll 1

STATE OF NEW YORK 2 0 1 9 T E N T A T I V E A S S E S S M E N T R O L L PAGE 1 VALUATION DATE-JUL 01, 2018 COUNTY - Niagara T A X A B L E SECTION OF THE ROLL - 1 CITY - North Tonawanda TAX MAP NUMBER ...

More info »
CDIR 2018 07 27

CDIR 2018 07 27

S. Pub. 115-7 2017-2018 Official Congressional Directory 115th Congress Convened January 3, 2017 JOINT COMMITTEE ON PRINTING UNITED STATES CONGRESS UNITED STATES GOVERNMENT PUBLISHING OFFICE WASHINGTO...

More info »
COMM 750 Network S Directory   508

COMM 750 Network S Directory 508

SM Provider Directory – Blue Network S UPDATED SEPTEMBER 2016

More info »
GPI 2016 Report 2

GPI 2016 Report 2

2016 TEN YEARS OF MEASURING PEACE

More info »
untitled

untitled

Chapter 6 Microbiology of non- CF bronchiectasis # J.E. Foweraker* and D. Wat Summary *Dept of Microbiology, and # Lung Defence Unit, Papworth Non-cystic fibrosis (CF) bronchiectasis is a complex diso...

More info »
1005 low stress bicycling network connectivity

1005 low stress bicycling network connectivity

MTI Low-Stress Bicycling and Network Connectivity Funded by U.S. Department of Low-Stress Bicycling and Transportation and California Department of Transportation Network Connectivity MTI Report 11-19...

More info »
139107

139107

Addressing Nitrate in California’s Drinking Water TECHNICAL REPORT 6: Drinking Water Treatment for Nitrate With a Focus on Tulare Lake Basin and Salinas Valley Groundwater Report for the State Water R...

More info »
Thriving on Our Changing Planet: A Decadal Strategy for Earth Observation from Space

Thriving on Our Changing Planet: A Decadal Strategy for Earth Observation from Space

TIONAL ACADEMIES PRESS THE NA This PDF is available at http://nap.edu/24938 SHARE     Thriving on Our Changing Planet: A Decadal Strategy for Earth Observation from Space DET AILS 700 pages | 8.5 ...

More info »
acp 16 3761 2016

acp 16 3761 2016

Atmos. Chem. Phys., 16, 3761–3812, 2016 www.atmos-chem-phys.net/16/3761/2016/ doi:10.5194/acp-16-3761-2016 © Author(s) 2016. CC Attribution 3.0 License. Ice melt, sea level rise and superstorms: evide...

More info »
Managing the Risks of Extreme Events and Disasters to Advance Climate Change Adaptation

Managing the Risks of Extreme Events and Disasters to Advance Climate Change Adaptation

MANAGING THE RISKS OF EXTREME EVENTS AND DISASTERS TO ADVANCE CLIMATE CHANGE ADAPTATION SPECIAL REPORT OF THE INTERGOVERNMENTAL PANEL ON CLIMATE CHANGE

More info »