Example R programs and commands 1. Data lists; functions; graphs # # Everything between "#" and the end of a line is a comment. # ###### PLOT TABULATED DATA x <- c(1.1, 1.7, 2.0, 2.1, 1.9, 1.5) # assign "x" a column of data # NOTE: "<-" means assignment; read it as "gets". "=" can be used as well. x # display the value of "x" x[1] # first element of "x" x[4] # fourth element of "x" length(x) # number of elements in "x" plot(x) # by default, plot points (i,x[i]) for i=1,...,length(x) plot(x,type="line") # piecewise linear interpolation plot(x,type="l") # "help(plot)" shows the other abbreviations plot(x,type="l",asp=10) # y/x aspect ratio >> 1: tall plot(x,type="l",asp=0.1) # y/x aspect ratio << 1: wide plot(x,type="l",col="red") # "colors()" lists the choices ###### PLOT A SAMPLED FUNCTION 0:100 # list the integers 0,1,2,...,100 t <- 2*pi*(0:100)*0.01 # R knows about pi y <- sin(t) # evaluate sine at all "t" values plot(t,y) plot(t,sin(t)) plot(t,sin(t), type="l", col="dark green") ###### PLOT SEVERAL FUNCTIONS ON THE SAME AXES t <- 2*pi*(0:100)*0.01 # same sampling of [0,2*pi] as before data2 <- cbind( sin(t), cos(t) ) # bind two columns into a matrix matplot( data2, type="l" ) # plot column 1 in black, column 2 in red (default) matplot( data2, type="l", col=c("lime green","purple")) # if you prefer other colors data3 <- cbind( sin(t), cos(t), exp(-t) ) matplot( data3, type="l" ) # col.1 black, col.2 red, col.3 green (default) matplot( t, data3, type="l" ) # put actual "t" values on the abscissa ###### DEFINE A FUNCTION OF ONE VARIABLE # Haar's function: # haar(t) = 1, if 00) { if(t<=1/2) { out <- 1 } else { if(t<=1) { out <- -1 } } } return(out) } ###### GENERALIZE TO ALLOW VECTORS AS INPUT: vhaar <- function(vt) { # code to define the function "vhaar" follows: out <- vt # makes a vector of the same length as input "vt" for(n in 1:length(vt)) { out[n] <- haar(vt[n]) } return(out) } # Plot the generalized function so defined: t <- (-10:110)*0.01; # abscissa values -0.10, -0.09,..., 1.09, 1.10. plot(t,vhaar(t), type="l") # Plot the function and its dilate by 2 on the same axes: matplot(t,cbind(vhaar(t), sqrt(2)*vhaar(2*t)), type="l") # NOTE: "sqrt" is the square-root function # NOTE: "2*t" multiplies each element of "t" by 2. # NOTE: "sqrt(2)*vhaar" multiplies by 2 each element of the vector returned by "vhaar". # Plot the function and its dilates and translates on the same axes: matplot(t,cbind(vhaar(t), sqrt(2)*vhaar(2*t), sqrt(4)*vhaar(4*t-3) ), type="l") # NOTE: "4*t-3" subtracts 1 from each element of "4*t". ###### READ PREVIOUSLY DEFINED FUNCTIONS FROM A FILE # If "haar" and "vhaar" are defined in file "haar.txt" in the current folder, # then their definitions may be recalled via: source("haar.txt")