CSCI N207 Data Analysis Using Spreadsheet Loops Department of Computer and Information Science IUPUI
For Loop for (var in list) {statement(s)} Get each value from the list, assign the value to a variable, then use the variable in the statement(s) To show the value inside of the loop, you must use the print function.
For Loop for (var in list) {statement(s)} Get each value from the list, assign the value to a variable, then use the variable in the expression
For Loop Exercise: use a “for loop” to print out even numbers between 1 and 10 Use a “for loop” to print out odd numbers between 1 and 10 Use a “for loop” to print out all the numbers from 10 to 0.
While Loop while (condition) {statement(s)} As long as the condition is true, run the statement(s) Exercise: use a while loop to print out even numbers between 1 and 10 Use a while loop to print out odd numbers between 1 and 10 Use a while loop to print out all the numbers from 10 to 0.
Save Code in .R File You can save your code into a .R file so that you code is stored in a separate place. Later, when you need to work on the code again, simply have R open up this file. Steps Create a script file: File -> New script An R Editor window will open. Type in code in the Editor window. Beware that now you have two windows open, one is R Console and the other is R Editor. Both windows can be moved on the screen. Sometimes one window may be hided behind another. If you cannot the other window, move the front window around until you see the other one.
Save Code in .R File Highlight the codes you want to run and click on “Run line or selection” button. The codes will be copied into R Console and run for you. Save the codes in R Editor: Highlight the R Editor window, and click on the save button. It will ask you for a file name. Find the folder you want to save to and give a file name. The file will be saved as a .R file, e.g. if the file name you entered is “loop”, the file saved will be loop.R Open up the .R file again: File -> Open script and locate the .R file.