Math 4600 Lab 1 Additional Resources January 15, 2015 1 Writing Commands in a .R text file Why should I save my commands in a .R text file? • In Unix it is difficult to save your commands. By saving your commands, you can easily reproduce your work at a later time. • If something is wrong and you need to slightly change a command, it is easier to edit your code. How do I save my commands in a .R text file? • First open your R folder in your home file network. Now somewhere in the open space in the folder right click and select ”create new file”. • You should now see a new empty file in the folder. Click on it and name it filename.R (substitute filename for what you would like to save the file as) • Now open the file. When you do it should open into a program called gedit. Gedit is a text editor like notepad in windows. • Now in our filename.R file we can type the commands that we would like to enter in R. How do I use the .R text file? • Gedit is not R, so we will need to then copy and paste our commands into R in the terminal. • Entering code line by line quickly becomes impractical for sophisticated programs. A better way is to ”source” the entire file all at once. • In the terminal, type source(”filename.r”) to run that entire block of code. 1 2 How to plot a periodic function in R • Example: Let y = atb for t from 0 to T, and a = 2, b = 3. Suppose this function is T-periodic with period 1. Plot a few periods of this function. R code: a=2; b=3; T=1; dt=0.02; y=matrix(0, nrow = T/dt+1, ncol = 3) t=matrix(0, nrow = T/dt+1, ncol = 3) for (i in 0:2 ) { tmin <- i*T tmax <- (i+1)*T t[,i+1] <- seq(tmin, tmax, by = dt) y[,i+1]=a*t[,1]^b } pdf("example.pdf") plot(t[,1],y[,1], main = "Plot of y=a*t^b", ylab = "y values", xlab = "t values", type = ’l’, lwd = 3, xlim=c(0,3*T), ylim=c(0,a)) lines(t[,2],y[,2], type = ’l’, lwd = 3) lines(t[,3],y[,3], type = ’l’, lwd = 3) dev.off() • Note: When you use the pdf function, the plot will be saved into your current directory as example.pdf. This makes it easy to print the plot using one of the printers in LCB 115. 2