For Loops in R

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi and welcome to another our labs tutorial where we will talk about loops there are different types of loops in our in this video we will be focusing on four loops and in the next video we will talk about while loops there are also repeat loops in our but for loops and while loops are the common ones that we will see in our video tutorials so in general with four loops we have the word for followed by a set of round brackets where we specify an index variable I is commonly used but it can really be anything that you want it to be we'll see in one of our examples that we use the word temp as an index variable and then we write the word in and we specify a vector next we have a set of curly brackets inside which we put multiple lines of code or commands these commands will be repeated once for each element of the specified vector as the variable successively takes on the values of that vector so let's start with an example of this general form so here in our studio we can write for I there's our variable in one to five and that's our vector print I squared that's our command and we get this nice list of numbers printed out so let's just visualize this a little bit here so here's what we type into our index variable is I the vector includes the numbers 1 2 5 and then we want I squared as the output for the first iteration of the loop or the first time the command print I squared was executed the index variable I was assigned the value for the first element of the vector so 1 so in this case since the command asks to print I squared we would get 1 squared as the output which is 1 in the second iteration of the loop I would be set to equal the second element of the vector so in this case 2 and then the output I squared would be 2 squared which is 4 and this continues until the command has been executed for all 5 elements of the vector and so we can compare our answers to those that we got from the our console and we can see that they are exact clear the same now there are several variations of this general for loop first of all the vectors specified in the loop does not need to be sequential so instead of using the sequence 1 2 5 we can use the concatenate function to specify the vector negative 3 6 2 5 & 9 and we can print I squared and close our curly brackets and we can see that it obviously still works also instead of writing our vector inside the loop we can define it beforehand like this so X gets concatenate negative 3 6 2 5 & 9 and we can call up our vector X and then we can write our for loop specifying X as the vector so for I and X print I squared we can also print more than one thing so for example instead of just printing I squared like we have been doing we can print both I and I squared so here is our vector X and we can say for I and X print concatenate I and I squared or print the vector containing I and I squared and there we go so here are the I values and here the I squared values you might have noticed that the output that we get from running a loop is not usable we can't really do anything with it we can look at it we can recopy the numbers but we can't for example take the mean of the output or add these numbers to an existing data frame but that's okay we can fix this small problem pretty easily so we'll go back to our first example of printing the squares of the numbers 1 2 5 the first thing we want to do is create an empty vector to store the five elements of our output and now we start writing out our loop like normal we say 4 I and 1 2 5 open curly brackets and this line of code states that the ice element of our empty storage vector is going to be filled by I squared so for example in the first iteration of the loop I is equal to 1 so the first element of the storage vector is going to be 1 squared and then we end off our code with a closing curly bracket and we can view our vector and you can see that we have certainly squared the numbers 1 to 5 and store them in this vector and that's really handy because now we can use these numbers so for example we can take the mean of them but what happens if we don't have a nice sequence starting at 1 what happens if we want to store the squares of our non-sequential vector X well we can certainly make another storage vector called storage too and we can execute the same command as before but we get a vector that has more than 5 elements and that has a 0 and some na values so our code really didn't work and that's not surprising because with the different elements of X as our index values we can see that we have a negative index which complicates things in itself and we also don't have 1 3 or 4 as indices so we are not correctly specifying what we want the first third or fourth elements of the storage to vector to be and then with vector indices of 6 & 9 we are referring to the sixth and ninth elements of the storage 2 vector when we only want five elements in the vector but what we can do is use the elements of a sequential vector instead of the elements of X as index values so here's our vector X and we can make yet another storage vector storage 3 it's empty right now and we're going to save for I and 1 2 5 the ice element of our storage 3 vector is equal to the ice element of our x factor squared so for example when I is equal to 1 the square of the first element of the vector X is going to be stored as the first element of our storage 3 vector and there we go now we probably won't ever want to just square number but here's a more applied example we can convert degrees Celsius to degree Fahrenheit so we have a vector containing temperatures and degrees Celsius and we specify that the corresponding temperature in degree Fahrenheit is degrees Celsius times 9 divided by 5 plus 32 and we can print the vectors containing all of temperatures and degrees Celsius and the temperatures in degrees Fahrenheit in a previous video on conditional statements we talked about how if statements on their own and combined if and else statements do not work on vectorized arguments so for example we can have a vector of temperatures and we can write a typical if an ALICE statement so if temp is greater than zero print warm LS print not so warm and we get our warning message now we already looked in our conditional statements video at one way to solve this problem and that was the if-else statement but another way to deal with this is to add the if and else statements to a for loop so for temp in this vector or for each of these temperatures if temp is greater than 0 print warm else print not so warm and we close both of our curly brackets and just like the FL statement this seems to have done the trick right so now we hopefully have a handle on general for loops and we can move on to something slightly more complex the nested for loop nested for loops take this general form so we have our first loop for variable 1 and vector 1 and just a reminder that this number sign allows me to put in annotations so I'm just reminding myself that this set of curly brackets belongs to the first loop next inside this first loop we add another loop so for variable 2 in vector 2 and we have our second set of curly brackets and we can keep doing this as many times as we please so I'm going to end with 4 variable n in vector n and representing any number and then finally you enter your commands now notice that each new level of this code has a different indentation in your our studio script this is just a nice way to break up and keep track of big chunks of code so don't get too overwhelmed by this mess we'll do an example and everything will look a lot nicer so we have 4i our first variable in 1 2 3 our first vector and we last another loop within so 4j our second variable and 1 2 2 our second vector print I plus J and then we close our curly brackets and we get this list of numbers so where did they come from well basically our code here is saying that we have three high values to loop through and 2j values to loop through and we have to find every combination of I plus J for first iteration of this first loop I will be equal to one and then while I is equal to one J can equal one so I plus J would be equal to two and then J can also equal two so I plus J would be three and then for our next iteration of our first loop I would be equal to two and then in the same way while I is equal to 2 J can be equal to 1 in which case I plus J is 3 or J can equal to in which case I plus J is 4 and we do this for a third value of I and in the end we have our output 2 3 3 4 4 5 which is exactly the same output that we saw in our studio at this point you might have noticed that loops are not the only means to a particular end so looking back at our very first example in this video where we simply raised each element of the vector to the power 2 we could have easily skipped the whole loop entirely we could have simply defined our variable X as 1 2 5 and then we could have created another vector I have called it loop list by squaring the elements of the vector X and so without using a loop we have achieved the same end result in our it is usually better to avoid loops as much as possible it's not so much a problem with the small bits of code that we've been practicing with but when working with large data sets our runs vectorized operations much more quickly and efficiently than loops but loops are often more transparent meaning that various programs use loops whereas vectorized equivalents are often program specific and loops are sometimes inevitable as well so it is good to learn them for listening to this our labs tutorial video if you found this useful you might be interested in our free online Moodle course or check out and subscribe to our YouTube channel
Info
Channel: Richard Webster
Views: 155,605
Rating: 4.9317613 out of 5
Keywords: for loops, R Studio
Id: h987LWDvqlQ
Channel Id: undefined
Length: 11min 33sec (693 seconds)
Published: Thu Jun 18 2015
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.