#lesson 17 Ocober 2007 #All R-commands that you need for this lesson #You can directly paste the commands/ this file into the R-window to try out the commands #Questions: see help function ?command, or ask me tlaepple@awi-bremerhaven.de ############# this letter is used for comments #?function shows the help for a function ?sin #There is no definition needed for simple (scalar) variables #but instead of =, <- is used #just assign name<-value a<-1 #Print the number on the screen: a #prints only on the console print(a) #prints always #simple algebraic calculations a<-2*3 a<-a/2 print(a) # and print again #some vector / array functions #vectors / arrays normally need to be defined that R can distinguish it #from a scalar. y<-vector() #Produces an empty vector... #the size of vectors in R is dynamic... I can now assign y[1]... #Assign elements of the vector [i], Vectors index are starting with 1 y[1]<-1 y[2]<-2 print(y) print(y[1]) #very often vectors filled with equidistant values are needed x<-1:10 #x = vector (1,2,3,4,5,6,7,8,9,10) print(x) x<-(1:100)/5 # (0.2,0.4,0.6 ..........) print(x) #2D matrix #matrix(values_to_fill_the_matrix,dimension1,dimension2) data<-matrix(0,10,10) #creates a matrix with the dimensions 10x10, filled with 0's data<-matrix(1:100,10,10) #creates a matrix with the dimensions 10x10, filled with the values 1:100 (columnwise) #Accessing a matrix data[4,4] # Element 4,4 of the matrix data[1:4,1:4] #the upper left 4x4 part of the matrix data[1,] #First row of the matrix data[,1] #First column of the matrix #Control structures: #for loop: for (variable in array) { } for (i in 1:100) { print(i) } #plotting function #plot(y), plot y against equidistant steps y<-1:100 plot(y) #plot(x,y), plot y against x x<-(1:100)*5 plot(x,y) #note the changes in the x-axis #2D plotting functions #colour Contour + Colorbar: #filled.contour(x_coordinates,y_coordinates,data[x,y],zlim=c(minvalue,maxvalue)) #contour lines: #contour(x_coordinates,y_coordinates,data[x,y) #Example data<-matrix(1:100,10,10) #Create a 10x10 matrix filled with 1..100 filled.contour(data) #plot the data, automatic colorrange filled.contour(data,zlim=c(0,20)) #Set the colorrange to 0..20 contour(data) #Contour plot of the data # some examples for adding labels etc. to plots: #further parameters that can be used in plotting commands. #type = "l" : as line type #col = "color": plotting color #ylim = c(minval,maxval):Set the limits of the y-axis #main = "title": sets the title plot(x,y,col="red",main="example",type="l",ylim=c(1,70)) #overplotting: line(x,y) or line(y) is the same as the plot command but plots #a line on an already existing plot whereas plot is starting a new plot z<-x^2 / 100 plot(x,y,col="red",main="example",type="l",ylim=c(1,70)) lines(x,z,col="blue") #defining a function multiply <- function(x,y) { return(x*y) } print(multiply(3,4))