CS50R - Lecture 1 - Representing Data

CS50 · Beginner ·🔍 RAG & Vector Search ·2y ago

Key Takeaways

Introduces the R programming language and its applications in data science and visualization

Full Transcript

[Music] well hello one and all and welcome to cs's inroduction to programming with r my name is Carter zeni and I'm so excited to embark on this journey to learn this language called r with you now it's likely that you have never programmed before and if so that's okay but you might be asking what is a programm language actually anyway well it turns out a program language is something that we humans had created to actually talk to computers and have them solve problems for us and you might have heard of lines of code things actually tell computers what to do and you may have heard of programs being lines and lines and lines of code telling computer step by step what it is we want them to do and you might have heard as well there are other languages you could learn like C like python like R like JavaScript and so you could be asking yourself why would I learn R well R it turns out is this language built from the ground up to work with data and so if you are interested in data or some of these fields here like data science data visualization research or statistics or could be a language for you and although this course won't actually teach data science or statistics or the math behind them you will Emerge being able to use R for these disciplines now actually just recently researchers used R to model how covid-19 was spread and this is a visualization built entirely in R to model how covid-19 was spread on a cruise ship you might have also heard of 538 these data journalists who actually write articles with data they use R to analyze data to write their articles and share visualizations like this one so you actually understand insights from data to so without further Ado let's actually begin by writing our very first R prr program and to do that we'll need what's called an integrated development environment or an IDE for short now code at the end of the day is just text and you could use any text editor to write code but it turns out that when you actually want to write lots and lots of code it's helpful to have a tool to do that with and that's what this IDE will be doing for us now let me introduce you over here to this uh IDE called R studio now R studio is an IDE built EXP exclusively and particularly for R and here it is you'll notice off the bat that I have this kind of greater than sign here with a blinking cursor and this indicates what we're going to call the r console it's a place I can actually type R statements and have them run kind of line by line by line it's a great place for me to actually execute or to run one line of code at a time so let's actually type our very first line of our code here to create this file called hello . R which will write actual full-fledged program so to create a file using this console in R Studio I can type file. create open parentheses and close parentheses and then the name of the file I want to create so here I'm going to create in this case hello. r just like that now notice that hello. r ends in. R and that is actually very particular you might have heard of files ending in like jpg for images or maybe CSV for data files in R we denote our R programs with this capital r here so let me run this R statement here by hitting enter and now I should see well I see true kind of in yelling at me right here what this means is that this file was created and we'll also see this kind of bracket one here which will become more parent as we go on but it turns out that because R works a lot with data and lists of data it's often handy when you have lots and lots of data to give us an indicator of where in that list we are so we'll see this come in handy a bit more later but for now with this list of one value like true it just says one for now well where was this file created like I claim it was created but where was it created so R Studio has this file explorer that I can open on the side here and this file explorer shows me the contents of some particular folder on my computer even if you don't know much about computers you probably know about files and folders and so here it seems like I am inside of the users slj Harvard folder and inside of that folder R studio and R created for me this file called hello. R now R Studio works by default in a single folder and that folder it turns out is called our working directory if I ask R to create a file for me it will create that file in the working directory or if I ask it to find some data file and read it into my R program it will first search in that working directory for me here so let's open up this R file and actually write our first R program I'll type I'll uh hit this hello. R file icon here let me close my File Explorer for now cuz it's not important at this point but now I'm introduced to this new component of R studio in this case my file editor so as we saw before this R console down here is great for writing single r statement single lines of R code but this hello. R file is great for writing more than one line of code tens of lines hundreds of lines creating a full-fledged program here so I have this blinking cursor which means I can just go ahead and type some text and let's type in some text that will be our very first R program I'll type print p r i NT followed by an opening parenthesis and a closing one and inside those parentheses let me type hello comma space world just like this and now I've typed in some text my first line of R code I can save this file by clicking on this little save icon here or on Mac I could do command Des or on Windows I could do controls so let me hit the save button here and now this program is saved on my computer I could run it if I wanted to now you may be used to running programs by double clicking on them or finding some icon and clicking on that to open the program and run it but I don't see those icons here and that is intentional this is a program we've made ourselves which will require a different way of running it for us and even if you don't know much about computers you probably know computers speak this language called binary or like ones and zeros and right now we just have p r i n t parentheses quotes hello world like that doesn't look like ones and zeros to me so there has to be a way to translate or interpret the this R text we've written into ones and zeros the computer actually understands so R is more than a language it's also an interpreter that takes this text we've written and converts it to the ones and zeros the computer understands now to kick off that process that interpretation process I can actually click this button over here that says run so let me go down to the console first and let me clear the console so it's very clear what's happening here I'll type contr L to clear the console and now if if I go to this line of code line one and hit run I should see my first R program saying hello to the world over here so let's take a step back first though and think about what it is we have just done so here in R we have created our very first program and we've done so using something that's called a function now in languages like R and lots of others too you'll have access to these things called functions and functions let you tell the computer to take some action do something to solve some particular problem in this case our problem was displaying some text and this function that we saw called print helped us do just that so let's go back and show you this program again I come back to our studio we saw that this function is called print you can probably guess that yourself here and we know it's a function because I use these parentheses here this is convention in R to denote a function by by its name followed by parentheses followed by some particular input to that function now print when R the R Developers designed it it doesn't print some predetermined piece of text like it doesn't always print hello world doesn't always print hello to somebody else instead it prints the text that I want it to print and so we'll see as we learn programming together that these functions can take inputs and more precisely these inputs are called arguments to the function they're inputs that change how the function actually runs now what is it that print did well Down Below on the console here I see that it printed hello comma world and this is what's known as the side effect of the function something visual that happened side effects could also be something that happens via audio something else I see whatever happens as the function is running that is known as its side effect and this is our first program in R so far but let's pause here and ask what questions we have on our our studio or this first program we just wrote called hello world so question about why would use our studio as opposed to vs code well if you're familiar with VSS code you would know that it can work with a variety of languages like Python and c and others our studio though is tailor made to work with r and as we'll see later on in the course there's a lot of features of R Studio that make working with r much easier particularly with visualizations and plotting so we'll that later on in the course as well um also question about why would use r instead of python well python tends to be this really big language that can be used for lots and lots of things and you think of libraries in Python like numpy you can certainly do work like you would do in r with those libraries our studio though is more of a u more of a precise tool it's built from the ground up to work with data whereas python is more of a general tool for solving lots of different problems R then comes with some optimizations that make working with data a little more efficiently um but in general you could use either python with numpy or other libraries or R to work with data overall now a question from Louise would you show us how to change the working directory for the console so a great question about actually changing the working directory we saw earlier that our studio defaults to having some kind of working directory but you could change that if you wanted to well in R there is a function dedicated to changing that working directory and I can show you what that looks like over here let me come back to my R Studio environment and in particular my console so changing the working directory that really only requires one line of R code so I could then clear my console down below here and execute that line of code in the console the function to do so is uh set WD just like this and then in parentheses you can then type the path or the folder you want to change your working directory to so if you do want to do that you can use do it using the set WD function here now we've completed our very first hello world program um but odds are things aren't always going to go as smoothly for you if you're just beginning with programming and even if you're more experienced you might encounter these things called Bugs or these errors in your code so let me reproduce kind of uh intentionally here a bug that could happen in my program let's say as I was typing I didn't type print i instead typed PR let me save this program here and let me run it to see what happens I'll hit run and well now I see down in my console error in PR uh parenthesis hello world could not find function prin in this case so this error is hopefully telling me like look there is no function called PR and hopefully by seeing this I should then actually know well I didn't mean to type PR I meant to type print instead so I can go back and fix it and this process of actually going back and fixing our programs is known as debug finding those bugs in our code and getting rid of them by uh looking through these errors and talking to a colleague or trying to fix them overall so here let me go back and clear my terminal my uh console down below I'll run this line of our code or run this line of um this program here again and I'll see once again hello world so this is a pretty good program but I argue we could do a little bit better with it like we don't have to say hello to everyone we could try to say hello to a particular user and so our next step here will be to actually ask the user for their name and then say hello to that particular user now to get user input there is a function in R for that it's not print it's instead called read line so let's use the read line function here I'll type re e a d read line this is all one word and then parentheses opening and closing and it turns out that readline takes an argument to this argument will then be the prompt it prompts the user with so I'll ask the user what's your name just like this and I'll save the file here so let me go down and clear my console I'll then run this line of our code and I'll see what's your name I could type in this case my name is Carter hit enter and I see Carter so it's not so much a greeing as much it is just kind of saying my name back to me I think we could still do better than that as well let me clear here my console and ideally I want to say something like this I want to say hello Carter so I could use print again maybe on line two now I choose to say print and then hello comma Carter and I'll save this file again well now I have not just one line of R code but two and when R goes to interpret this program it will read these lines of code top to bottom left to right executing each function along the way way but it turns out that this run button over here it says run but what it really does is it only runs one line of R code at a time for example I could run just line one or I could run just line two but what we have here is really a full-fledged program it's more than one line of code it's two so to run the entire program I need to use a different approach a different button in this case and that button is this source button up top here Source in this case means to run the entire source file here so let me go ahead and source and let me say what's my name my name is Carter and I see Hello Carter but there might still be a bug in this program let's try it one more time let me clear the console I'll Source again and what if my name was like Mario from the Nintendo Universe I could type well my name is Mario hm hello Carter okay let's try it again I'll do source and I'll do uh maybe my name is Princess Peach so Princess Peach here and well still hello Carter so it seems to me like we need to do something more Dynamic than just printing out hello Carter we need to actually print what the user has given us at the console so for that we'll actually need this new uh Concept in programming called a return value functions don't just have arguments and side effects they also have return values and in this case readline will return to us as it's return value the user input you could think of it a bit like a metaphor of asking your friend to go out and ask somebody for their name and they might write it down and return it back to you the programmer so you can use it later on in your code that's kind of what return values are in this case but if I have a return value I'm going to need some place to store it some place to reuse it later on in my code and for that we'll need something called a variable or an object a variable is some name for a value that could change so let's see how we could use both return values and objects in R to make this program more Dynamic let me go to line one here and let me try to give this return value of readline a name I could reuse later on well if the user types in Carter I want to refer to that value via some name and maybe the right name is just simply name so I'll type name here and now if I want to store the return value of readline that is whatever the user typed in inside this object called name I could use this syntax these particular characters here the less than sign and a Dash and notice if we read this kind of right to left first readline will run as a function it will prompt the user for their input the user will type that input in and then readline will come back to us and give us back whatever the value is that the user typed in and then these of code over here name space less than this Dash here will store it underneath this name called name this Arrow this leftward arrow is called the assignment operator we're assigning whatever return value from readline to this new object called name so let me just for now get rid of this line two and just focus on this particular piece right now let me Source this file and now let me say my name is Mario I'll hit enter and I see nothing yet CU there's no print but now if I open up this new pane in our studio let me go ahead and go to my environment pane I'll actually see what the value is for this object we created called name so it seems like our studio is telling me that I have this object called name and its value now is Mario this is part of our environment the environment is the place we actually store our objects while our program is running so we can then reuse them later on in our code so I've kind of captured this user input and stored it in this object called name but let's see how we could use it now I'll come back to our studio and let me go back to line two and let me now print in this case let me print hello comma name just like this I'll kind of close my environment over here and now let me Source this particular file I'll type uh Mario it's my name and now hit enter and I see well hello name so this isn't exactly what we wanted I actually printed out literally hello comma name so I think we'll need to find some other solution here we solved one problem which was getting the user input and storing it somewhere but I mean how do we reuse that later on well if I'm being observant I might notice that what I'm really trying to do is combine some pieces of text like this text here is how hello comma space and the text I'm trying to combine is whatever the user typed in or that is whatever is being stored in this name object I have over here so I'm trying to combine hello commas space and this text from the user Mario now this is a common problem in programming trying to combine pieces of text so common that it actually has its own particular name this is called string concatenation where concatenation means combining together these various pieces of text or these strings so let's break it down and here of course we have the very first part of our greeting this is some piece of text or from here on out called a string a string because it's kind of characters strung together into one piece of text strings begin and end with these double quotes here so I have hello comma space and that is one particular string but then the user comes in and they type in their own string let's say like Carter and now my t ask is to combine these together into a single string and print that back out to the user so my goal here is to effectively this turn these two separate strings into one individual string now R handily enough comes with a function to do just this so let's explore that function here this function is actually called paste paste is in PA a s and paste allows me to concatenate various strings so let's try this one here if I want to use paste I use it the same way I would any other function I could use the function name and then opening and closing parentheses and then paste will take as input any number of strings I want to concatenate or paste together in this case so let's say the first string as we said is hello comma space now the next string is something new it's actually going to be whatever is stored in this name object over here so if I want to provide another input to paste I should actually separate it now with a comma so after the first input to paste the first argument I'll then give it a second input or a second argument and this one will be literally name in this case this object we stored that has that value the user themselves typed in and now paste its return value will be the combined version of these two strings so let's try it maybe I'll store the return value inside its own object called greeting I'll use the left Arrow this assignment operator to store the return value of paste in this object called greeting and then down in print here I won't print hello name literally I'll instead print whatever is stored in the object called greeting so as I run this let me open up my environment so we can see how these values change over time let me go ahead and click Source here my name in this case is Carter I'll hit enter and I see Hello Carter so if I go back to my my um environment here I see I not only have this object called name storing Carter I also have this object called greeting storing the concatenated versions of in this case the string hello uh comma space and then the string Carter itself but if you're being particular particularly observant here what do you notice as a bug in this program let me ask our audience here what do you notice as a bug in this program there are two spaces yeah there are two spaces so I only wanted one space but it seems I have somehow gotten two like greeting here has hello comma space space Carter so why is that well I could spend a lot of time kind of banging my head wondering why is this not working or I could look at something called documentation so programmers when they write functions like paste they also write documentation that tells me exactly how to use paste and what the affected output of paste might be so let's look then at the documentation for paste I can actually access documentation if I use this special character in R called the question mark and if you uh want to remember this I trying to think of like just being confused like what do I do the question mark is that symbol then I follow with the function name in this case paste so now over on the right hand side let me make this bigger for us over here I'll actually see the documentation for paste whoever created this function called paste helpfully wrote this documentation to guide me on how to use paste itself so I'll see up top the goal of paste is to concatenate strings like we just talked about that much is obvious but down below I think is the helpful part this down below will tell me what kinds of inputs paste could potentially take and I'll see the same thing we saw before paste Follow by some parentheses with various what we'll call parameters here so these are still inputs to paste but they're potential inputs and because they're potential ones we'll call them parameters arguments are the actual values we passed to paste parameters are the potential ones here now I see if I go down here some dot dot dots these dot dot dots mean that paste could take really any particular number of arguments that could be any number of strings I want to concatenate in this case I then have over here though this named parameter called sep and it says sep equals quote unquote with a space in the middle now this is what's called a named parameter it has a given name because it has a special uh use case in this case of of paste now the equal sign means the default value for this parameter is going to be this value here the quote space unquote so it seems like this parameter called sep might be what's making this extra space actually happen in my output and if I go back to the documentation over here let me scroll down a little bit so we can see I'll go down to the arguments and you can see that sep is in fact a character string to separate the terms so my job now is to think about what would I change the value of sep to B to remove that extra space well I can go back to my program and ideally I don't want anything any characters to default separate the strings I just want to have them put together with no spaces in between so to use this named parameter called sep I can then have another input to paste I could follow with a comma just like this and then use that named parameter sep in this case and set it equal to some new kind of value in this case quote unquote or really no spaces at all so let's try this now I'll um clear my console I'll run source and I'll type Carter again and now I'll see hello comma space only one space Carter now if you're like me you might think I'm going to often want to concatenate strings that don't have any spaces in between them and it's going to be a lot of typing to always type comma SE equals quote unquote if you're writing many lines of code you don't want to do this over and over and over again and in fact some R users got tired of just this and they wrote their own function where the default is sep equals quote unquote nothing this function is called simply paste zero paste zero where zero means there's nothing between these concatenated strings I now don't need to supply the input set because the default will always be no particular space at all now I'll rerun this program source and say Carter and I'll get that same output now one other way to do this because there's always more than want me to do something is I could maybe just omit the space Al together like I could say hello comma and make that my string and I could then assume that paste will go ahead and actually add the space in for me I could run Source just like this type in Carter and now I'll see Hello Carter again completing our program here so let me pause and ask what questions we have on paste string catenation or our program so far uh so what's the difference between uh the past function and the cat function because I think both of them are used for string conation yeah good so if you are famili or familiar with r you you might have also heard of this function called cat and Cat itself stands for concatenation um cat and paste have two uh similar use cases they both involve combining strings together but they have slightly different outputs so cat has the side effect of printing whatever you've concatenated to the console uh paste on the other hand does not paste only returns to you kind of silently the concatenated version therein and you can then use that later on in your code cat I believe doesn't actually return to you the result just kind of prints it to the screen as a side effect so two very different use cases but the same kind of goal here all right let's continue and let's keep improving our program here so one thing you might notice is that I have this object called greeting and I'm just on the next line using that very same object and this seems just a little bit redundant because I'm just storing this value from paste in reading and immediately giving it back to this function called print well to have this same result and actually reduce some number of lines of code I could do the following I could actually remove the idea of storing the result of paste in any given object and I could simply run paste and immediately pass the value or the return value from paste as the input to print now this is arguably the most complicated line of code we've seen so far so let's break it down just a little bit this what we're doing right here is known as function composition I'm making one function run and then immediately passing the output of that function as input to the next so this is our line of R code and we said before that R runs lines of code kind of line by line top to bottom left to right and that's mostly true but in this case we see there's more than one function to run or action to take on on this particular line of code so what is r to do well what R will always do is look first for the function that is innermost in the parentheses so in this case that is the paste zero function that is concatenating or combining hello um comma space and then name over here now what this will do is make the return value of hello comma let's say space Carter and then pass that immediately as input into print just like this and once that's done print can then do its job and of course just print out something like hello Carter so always think about the innermost function running first and passing its return value as the input to the next innermost function and so on and so forth so let's go ahead and try this out I'll come back to our studio here and here I have paste as opposed to paste zero but kind of the same thing as we saw before let me go ahead and hit cck Source here I'll type Carter and we'll see that I get the very same result without storing in this case an additional object now an extension of this might be the following I could take read line I could take read line and notice how it's just simply storing the value in name which I immediately pass as input to paste I could do this I could take read line and put this right there and now I have three functions nested inside of each other but let me actually ask you why might this not be a good idea let's think about other people who might read this code or think about working together on projects like why might I not want to do this or go this far with the design of my code here as uh I think because it doesn't explain the code perfectly uh to the user yeah it's kind of hard to read like if I saw this line of code here I would have to kind of think to myself okay which function is happening first well it looks like it might be readline and then what happens next okay paste happens next so it's a lot for me to think of as I'm reading this program and even though it is shorter I would say it's not necessarily better so these are questions about the design of programs which way to write the code is better um we have the same result so they're both correct but there are still different ways to design it and trade-offs to consider in terms of readability as well so let's come back and let's try to fix up this program a little bit I would argue that it's probably cleaner if we instead have readline on a separate seate line of code I'll put this first on line one and I'll go back to storing this object called name and I'll pass it in as input to paste here just like this now we just talked about the idea of making our code more readable and it turns out that R comes with a feature that can let me do just that I can actually Leave myself some notes to self called comments that will help me understand my code using the English language so if I want to write a comment or a note to my myself in my code I can do so by typing this hashtag here followed by a space and I can then type the comment I want to type I could say maybe this line asks user this line asks user for asks user for name just like this and the next line well what does this line of code do this line of code says hello to user just like that now comments by convention go on the line above the line of code they are talking about so in this case I know this comment on line one refers to the code on line two and this comment on line four refers to the line of code on line five but comments are very helpful when you actually are working on a larger project you come back later don't know what you did comments can then help you understand exactly what to do and what you had done prior as well so this was our hello world program we said hello to the world we said hello to some users let's get working with some data now and and in one case we might want to work with data in terms of let's say counting votes for an election so let's go ahead and try to simulate an election between some fictional characters from the Nintendo Universe in this case Mario Peach and Bowser so to create this new program I'll in I'll go go to my console again and I'll type file. create and in this case I want to count some votes so I'll call this program count. R just like this I'll hit enter and I'll see that this file was created so now if I open up open up my window over here and go to files I should now see that count. R is available to me as a file to write this program in I'll open up count. R and now I have a blank slate of a program to write so we have three candidates to keep track of votes for Mario Peach and Bowser so let's let the user actually type in those votes and return to them or print out the total number of votes that happened in this election so maybe I will ask the user using readline to enter votes for Mario just like this and I'll also ask the user to enter votes for peach just like this Princess Peach and I'll also use readline to ask the user to enter votes for Bowser just like this now it's likely I want to use whatever the user types in later on in my code so why don't I store the return value of readline in an object I could reuse later on maybe I'll call this one Mario and this one peach uh and this one let's go for Bowser just like this so I'll save it and again the goal was to kind of add up these total number of votes well maybe I'll make a new object called total to store those total number of votes and I'll um have something that will assign that total number here well it turns out that to actually add data together I can use in R this plus sign plus operator so I'll say Mario plus Peach plus Bowser and that should return to me the total number of votes the user actually entered in the console and if I want to then print that back out to the user well I could use print and paste again so I'll use print paste and then total votes no space cu no paste will actually add it for me and then total itself down below here so a few things we've seen before and a few new things um what's new is this arithmetic we've seen now we just used this plus operator to add together some numbers and R has more than just the plus operator it has several others as well it has addition as we just saw with a plus sign subtraction with this minus sign or a dash multiplication with this star or asterisk operator and division just like this with the forward slash here there are other operators 2 that we'll talk about later on in the course but for now these four will help you do some basic arithmetic that can help us solve some uh really interesting problems in this case so let's come back let's run our program I'll come back to our studio and I think this should work I'll go ahead and run source and I'll enter votes in this case for Mario maybe I'll say Mario has 100 votes and Peach has 150 and Bowser has 120 and now I should see the total number of votes that were cast in this election I'll hit enter and I'll see another error it says error in Mario plus Peach non-numeric argument to Binary operator H the other error element was easier to understand this one's less easy so at least it tells me where the error happened it said it happened in Mario plus Peach so it seems like maybe on line five here when I tried to add the user's input for Mario to the user's input for peach and it says the reason a non-numeric argument to the binary operator so the binary operator I'll tell you is this plus sign here but the non-numeric argument it seems like it's telling us that Mario and Peach those aren't numbers at all so let's take a peek at our environment where we stored those actual objects let me take a peak over here and what will we see if I go to environment maybe remove this down below here I see some old some old things here like greeting and name that I didn't get rid of before but I I also see Bowser Mario Peach and what do you notice well it seems like before we had let's say greeting that was a character string and we knew it was a character string because it had quotes around it right but we see the same thing now for Bowser and for Mario and for peach which implies to me that these are still character strings they're not so much numbers now I think R is now telling me that it needs numbers to be able to add these things together it can't add the character 120 with the character 100 these need to be actual numbers so let's see what we can do about that let's come back to our studio here and let's actually introduce this new idea of a data type or a storage mode in R we have various ways of storing data we've seen one so far called a character string but there are lots of others too among them are these characters we just saw and then double and integer these are both numbers double refers to a decimal number like a 1.5 for instance integer refers to a whole number like just one plain and simple and there are more too but these are the ones that matter here so it seems to me like readline when it returns us the input from the user it returned a data type of character or a storage mode of character but what I really need to to add these numbers together is a double or an integer these numeric storage modes down here so let's see if there are functions that could help us actually are so there among them are um uh this idea of as. character as. double and as. integer these are functions that actually take some particular object and convert them to the storage mode we want so I could give as input to as do integer some object and it will return to me then that same object but now as as integer and this is known as coercion changing the storage mode of an object using a function like this to convert it to some particular new storage mode so let's try these out I'll come to our studio again and I will then try to convert this data to an integer before I actually add it together let's on line Five and Below let me go ahead and use as. integer I'll type as. integer Mario and as. integer Peach and as. integer Bower well in this case hopefully that should work let me go and hit Source again and I'll enter Let Me Clear My terminal first I'll enter 100 votes for Mario 150 for peach and 120 for Bowser and I still see that they're not numeric so one common mistake is that simply running the function here is not enough to change change this particular object I need to then reassign the return value of this of this function to the object itself so for instance if I want to update the value of Mario I need to reassign it as the return value of as. integer or I need to update the value of peach by reassigning it as the return value of this function here and same with Bowser as well and now I think if I run this fingers crossed let me come my console again run source and I'll choose 100 for Mario 150 for peach 120 for Bowser and I'll see the total votes was 370 now this is a bit of a longer program we've seen before this is like 11 lines total there's probably a way to actually clean this up a little bit though one way would be to immediately try to convert the input from the user to an integer so I could use function composition and I could instead immediately pass pass the return value of readline as the input of as. integer and same for peach and same for Bowser let me actually clean this up have a parentheses there and a parentheses here and now I can get rid of lines 5 through 7 and now it's just a little bit shorter and I'd argue that this is actually a good use of this particular um function composition because now I'm immediately seeing that okay I want an integer from the user let me go ahead and try this again I'll click source and now I'll see 100 150 120 and I still see 370 now this is pretty good but let's think of a a corner case or some other scenario where there are more than three candidates well in this case I don't want to be stuck always typing plus you know plus plus some new candidate what I want to use instead is likely a function called sum now R because it works so often with data has this function called called sum that can take as input any number of numeric arguments and sum them up for me so let's use sum instead in uh total here I actually want to return the result of calling sum with three arguments three inputs the first is Mario second is Peach and the third is Bowser so now some will look at all three of these numbers add them up and store them now in total so I'll clear the console run source and I'll type in 100 votes for Mario 150 for peach and 120 for Bowser and now I'll see total votes was 370 as well so we've improved our program so far and we've seen how to use these storage modes to add data together now what questions do we have on this program here or storage modes in general can we enter an argument like an array through this some function yes I heard you mention this idea of an array and if if you're familiar with other programming language you might have heard this idea of an array like some list of data and the question is could we give some not these three separate values but actually an array or some list of data uh in fact we can and I suggest we actually take like a five minute break and come back to learn more about these structures we can use to represent data just like that see you in five well we're back and so we've seen so far how to write programs that take user input but odds are as you write more R programs you don't rely so much on the user to actually enter data for you for you you'll instead read data from a file like a CSV file for instance so let's take a look way at ways you can actually represent data and how to use those representations now in R well you often find data is stored in these things called tables and here is an example table I'm trying to represent here candidates like Mario Peach and Bowser and the number of votes they received at the poll so this is actual physical polling location and VIA mail from mail-in ballots let's say so notice how this table has both rows this kind of horizontal orientation and columns this vertical orientation in particular there are three columns with names so one is candidate where I have the names of my candidates in this case Mario Peach and Bowser over here I have this column called pole represent presenting the number of ballots or votes that Mario Peach and Bowser received at the actual physical polling location so let's say Mario got 37 votes Peach 43 and Bowser 84 now well for the male column there's also going to be some numbers here as well let's say Mario got 63 mailin votes peach got 107 mailin votes and Bowser 36 so this then is our table of rows and columns and one kind of analysis we might want to do on this table is called a tabulation that is figuring out how many votes we received by poll or by mail and also how many votes each candidate received so we could asked the question how many votes did Mario receive overall that would be a tabulation along these rows here we could also ask how many votes we receive at the actual physical polling location that would be a tabulation along Ong this column here so these are two questions we actually answer using R but r at least immediately doesn't give us a way to represent a table exactly like this if you want to store this data kind of long term you need to do so in a file and one popular way of representing data like this inside of a file is to use a CSV file or a comma separated values file so here is the same representation of that data but now as a CSV file notice here I have those same column names candidate pole and maale and I still have those same column values Mario Peach Bowser 37 4384 and so on but what you might notice is that the columns are now separated using these commas and that makes sense this is a comma separated values file or a CSV file every row is still on its own Row in the file but now these columns are presented now with these commas so let's see how we could use R to read in this CSV file and give us an actual table of data to work with I'll come to our studio here and one of the first things I actually might want to do is clean up my working space if I want to see what's currently in my environment I can type this function LS at the console and hit enter and now I'll see all the objects that I still have in my environment some from some prior programs now I probably want to get rid of these as I'm writing some brand new program so to do that I could use this function called RM which stands for remove whereas LS stands for list I could use RM and it turns out that RM takes a named argument called list that is the list of values I want to remove from my environment and I'll say that this list is what was the result of calling LS that is it will include Bowser greeting Mario name Peach and total all of these prior objects I no longer want anymore so I'll enter on this and I'll type LS again and now I'll see character parentheses zero which it basically says there's nothing here right now there's an empty string nothing at all in my environment so now my environment is clean there are no objects here let me actually create a new program one called tabulate so I'll do file. create tabulate R to represent how we're going to tabulate this table of data and find the number of votes for each candidate and each voting method let me do enter here and I'll see that file was created for me I'll go to my file explorer and open up tabulate do R so actually notice here in my file explorer I do have this file named votes. CSV if I click on it I can actually see if I click view file here what's inside this file and notice here I have the same exact thing we saw on the slides candidate comma pole comma mail and then one row for every Row in my data set so our goal then is to read this CSV and store it in R so you can actually get back a table of data to work with now entirely in R what one function I could use to read data from a file like this is actually called read.table read.table and I can give read.table the name of the file I want to read or to open to load inside of R so that file name was votes. CSV and because votes. CSV is in that working directory I can just refer to it by its plain and simple name so a read that table has a return value it's going to give me back a table of data so I'm going to actually store that let's say in this table called votes and now let me run just this line of our code I can do that by hitting run over here or on map I could type command enter on Windows I could type control enter I'll do command enter on Mac and now I see according to the console I have now read the votes um data table here so if I want to see what it looks like there are a few ways to do that I could actually look at my environment let's try that first I'll go to environment and I'll see the following that votes seems to have four observations of one variable hm so observations actually refers to the number of rows in this table I've gotten back and variable refers to the number of columns I've gotten back and you might already be thinking this doesn't seem right because I thought it had at least three rows and I thought it had at least three columns and I seem to have four rows and one column so something might be wrong here if we want to see exactly what happened I can use this function called view capital V and I can pass as input the object I want to view in this case if I run this line of our code I should now see a separate tab that shows me exactly what is stored in this object and I would say these results are not good this is not what I want to look like because again we only have one column that R seems to have named V1 and instead of three rows there are four where one row is actually the names of the columns that I wanted uh to be the case this is just not what we want so it seems like read.table needs more information on how to read this particular file and one thing it might need to know is what is the separator between each of my columns well because this is a CSV file that separator is none other than a comma so read.table like paste takes a named argument called sep and this will set to be an actual comma so now read.table knows to look for the commas and use those to identify what is a column inside of this data file so let me then rerun this line of code and now view it and I'll see we're getting better so here I have three columns although one is called V1 one is called V2 there is called V3 and I still have four rows so it's not quite there but we're getting close one other argument to read.table is in fact this one called header header so header um can be either true or false yes or no do the column names exist in this file in this case they do so I'll say header equals true I'm essentially saying that yes the column names are inside this file you should look for them and you should use them so let me rerun this I'll rerun line one and now line two and now I think we're in a pretty good place so R actually has stored inside its environment this table for me to use I see three columns candidate pole and male and now three rows um I could do something to make this a little more readable often we have lots of arguments to these functions it's better to put them on separate lines so according to the style guide for r that kind of tells me how I should be structuring my file I should do something a bit like this I should put each argument on a new line in my code and then make sure that this closing parentheses is all the way against the left hand side so this allows me to more quickly see what arguments I have of supply to read.table but the result is exactly the same of course now CSV files are pretty popular and it doesn't make sense to me to always be writing sep equals comma header equals true and in fact people who work with r they come up with their own function called read.csv to make this much easier for us as programmers so instead of read.table which can work on a variety of of actual data files I'm I might instead use read.csv because of course I have simply a CSV here so let's try this I'll run just read.csv given the file name hit enter here and enter here and it's the same result but now with much less typing much fewer arguments read. CSV just seems to know more naturally how to read these files called CSV files Okay so we've successfully read this CSV file but the next question is what exactly has it given back to us like certainly it's a table but in R this table ha

Original Description

*** This is CS50, Harvard University's introduction to the intellectual enterprises of computer science and the art of programming. *** TABLE OF CONTENTS 00:00:00 - Introduction 00:00:20 - What is R? 00:01:56 - hello.R 00:07:39 - Functions in R 00:12:49 - readline 00:19:12 - paste 00:29:08 - Function Composition 00:34:19 - count.R 00:39:36 - Storage Modes 00:45:22 - Tables 00:49:48 - tabulate.R 00:55:50 - Data Frames 1:01:48 - Vectors 1:14:54 - write.csv 1:17:49 - voters.R 1:26:14 - Special Values 1:30:35 - Factors *** HOW TO SUBSCRIBE http://www.youtube.com/subscription_center?add_user=cs50tv HOW TO TAKE CS50 edX: https://cs50.edx.org/ Harvard Extension School: https://cs50.harvard.edu/extension Harvard Summer School: https://cs50.harvard.edu/summer OpenCourseWare: https://cs50.harvard.edu/x HOW TO JOIN CS50 COMMUNITIES Discord: https://discord.gg/cs50 Ed: https://cs50.edx.org/ed Facebook Group: https://www.facebook.com/groups/cs50/ Faceboook Page: https://www.facebook.com/cs50/ GitHub: https://github.com/cs50 Gitter: https://gitter.im/cs50/x Instagram: https://instagram.com/cs50 LinkedIn Group: https://www.linkedin.com/groups/7437240/ LinkedIn Page: https://www.linkedin.com/school/cs50/ Medium: https://cs50.medium.com/ Quora: https://www.quora.com/topic/CS50 Reddit: https://www.reddit.com/r/cs50/ Slack: https://cs50.edx.org/slack Snapchat: https://www.snapchat.com/add/cs50 SoundCloud: https://soundcloud.com/cs50 Stack Exchange: https://cs50.stackexchange.com/ Telegram: https://t.me/cs50x Threads: https://www.threads.net/@cs50 TikTok: https://www.tiktok.com/@cs50 Twitter: https://twitter.com/cs50 Twitter Community: https://twitter.com/i/communities/1722308663522594923 YouTube: http://www.youtube.com/cs50 HOW TO FOLLOW DAVID J. MALAN Facebook: https://www.facebook.com/dmalan GitHub: https://github.com/dmalan Instagram: https://www.instagram.com/davidjmalan/ LinkedIn: https://www.linkedin.com/in/malan/ Quora: https://www.quora.com/profile/David-J-Malan T
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from CS50 · CS50 · 0 of 60

← Previous Next →
1 Hello, World: Hadi Partovi
Hello, World: Hadi Partovi
CS50
2 Content Distribution and Archival in a Digital Age
Content Distribution and Archival in a Digital Age
CS50
3 CS50 2014 - Week 1
CS50 2014 - Week 1
CS50
4 CS50 2014 - Week 3
CS50 2014 - Week 3
CS50
5 CS50 2014 - Week 0, continued
CS50 2014 - Week 0, continued
CS50
6 CS50 2014 - Week 4
CS50 2014 - Week 4
CS50
7 Week 3, continued
Week 3, continued
CS50
8 Quiz 0 Review
Quiz 0 Review
CS50
9 CS50 2014 - Week 3, continued
CS50 2014 - Week 3, continued
CS50
10 CS50 2014 - Week 7
CS50 2014 - Week 7
CS50
11 CS50 2014 - Week 7, continued
CS50 2014 - Week 7, continued
CS50
12 Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
Breaking Through The (Google) Glass Ceiling by Christopher Bartholomew
CS50
13 Introduction to Amazon Web Services by Leo Zhadanovsky
Introduction to Amazon Web Services by Leo Zhadanovsky
CS50
14 CS50 2014 - Week 9
CS50 2014 - Week 9
CS50
15 How to Build Innovative Technologies by Abby Fichtner
How to Build Innovative Technologies by Abby Fichtner
CS50
16 Light Your World (with Hue Bulbs) by Dan Bradley
Light Your World (with Hue Bulbs) by Dan Bradley
CS50
17 Building Dynamic Web Apps with Laravel by Eric Ouyang
Building Dynamic Web Apps with Laravel by Eric Ouyang
CS50
18 CS50 2014 - CS50 Lecture by Steve Ballmer
CS50 2014 - CS50 Lecture by Steve Ballmer
CS50
19 CS50 2014 - Week 10
CS50 2014 - Week 10
CS50
20 This is CS50 with Steve Ballmer?
This is CS50 with Steve Ballmer?
CS50
21 Meteor: a better way to build apps by Roger Zurawicki
Meteor: a better way to build apps by Roger Zurawicki
CS50
22 Data Analysis in R by Dustin Tran
Data Analysis in R by Dustin Tran
CS50
23 Data Visualization and D3 by David Chouinard
Data Visualization and D3 by David Chouinard
CS50
24 CS50 2014 - Week 6
CS50 2014 - Week 6
CS50
25 Build Tomorrow's Library by Jeffrey Licht
Build Tomorrow's Library by Jeffrey Licht
CS50
26 CS50 2014 - Week 9, continued
CS50 2014 - Week 9, continued
CS50
27 Essential Scale-Out Computing by James Cuff
Essential Scale-Out Computing by James Cuff
CS50
28 iOS App Development with Swift by Dan Armendariz
iOS App Development with Swift by Dan Armendariz
CS50
29 Sam Clark Leads Yale Students on Tour to CS50 at Harvard
Sam Clark Leads Yale Students on Tour to CS50 at Harvard
CS50
30 3D Modeling and Manufacture by Ansel Duff
3D Modeling and Manufacture by Ansel Duff
CS50
31 CS50 2014 - Week 5, continued
CS50 2014 - Week 5, continued
CS50
32 hello, world
hello, world
CS50
33 CS50 2014 - Deep Thoughts - Hash Table
CS50 2014 - Deep Thoughts - Hash Table
CS50
34 CS50 2014 - Deep Thoughts - Binary Tree
CS50 2014 - Deep Thoughts - Binary Tree
CS50
35 CS50 2014 - Deep Thoughts - Scratch
CS50 2014 - Deep Thoughts - Scratch
CS50
36 CS50 2014 - Deep Thoughts - MySQL
CS50 2014 - Deep Thoughts - MySQL
CS50
37 LaunchCode Visits CS50
LaunchCode Visits CS50
CS50
38 CS50 Live, Episode 100
CS50 Live, Episode 100
CS50
39 CS50 Field Trip to Google
CS50 Field Trip to Google
CS50
40 This is CS50 AP
This is CS50 AP
CS50
41 Week 4: Monday - CS50 2011 - Harvard University
Week 4: Monday - CS50 2011 - Harvard University
CS50
42 Week 2: Wednesday - CS50 2011 - Harvard University
Week 2: Wednesday - CS50 2011 - Harvard University
CS50
43 Week 1: Wednesday - CS50 2011 - Harvard University
Week 1: Wednesday - CS50 2011 - Harvard University
CS50
44 Week 11: Monday - CS50 2011 - Harvard University
Week 11: Monday - CS50 2011 - Harvard University
CS50
45 Week 3: Wednesday - CS50 2011 - Harvard University
Week 3: Wednesday - CS50 2011 - Harvard University
CS50
46 Week 12: Monday - CS50 2011 - Harvard University
Week 12: Monday - CS50 2011 - Harvard University
CS50
47 Week 1: Friday - CS50 2011 - Harvard University
Week 1: Friday - CS50 2011 - Harvard University
CS50
48 Week 3: Monday - CS50 2011 - Harvard University
Week 3: Monday - CS50 2011 - Harvard University
CS50
49 Week 10: Wednesday - CS50 2011 - Harvard University
Week 10: Wednesday - CS50 2011 - Harvard University
CS50
50 Week 2: Monday - CS50 2011 - Harvard University
Week 2: Monday - CS50 2011 - Harvard University
CS50
51 Week 9: Monday - CS50 2011 - Harvard University
Week 9: Monday - CS50 2011 - Harvard University
CS50
52 Week 7: Monday - CS50 2011 - Harvard University
Week 7: Monday - CS50 2011 - Harvard University
CS50
53 Week 5: Monday - CS50 2011 - Harvard University
Week 5: Monday - CS50 2011 - Harvard University
CS50
54 Week 5: Wednesday - CS50 2011 - Harvard University
Week 5: Wednesday - CS50 2011 - Harvard University
CS50
55 Week 7: Wednesday - CS50 2011 - Harvard University
Week 7: Wednesday - CS50 2011 - Harvard University
CS50
56 Week 8: Monday - CS50 2011 - Harvard University
Week 8: Monday - CS50 2011 - Harvard University
CS50
57 Week 9: Wednesday - CS50 2011 - Harvard University
Week 9: Wednesday - CS50 2011 - Harvard University
CS50
58 Week 8: Wednesday - CS50 2011 - Harvard University
Week 8: Wednesday - CS50 2011 - Harvard University
CS50
59 Week 10: Monday - CS50 2011 - Harvard University
Week 10: Monday - CS50 2011 - Harvard University
CS50
60 Week 2: Wednesday - CS50 2010 - Harvard University
Week 2: Wednesday - CS50 2010 - Harvard University
CS50

Related Reads

📰
Optimizing RAG at Scale: Chunking, Retrieval, and the Bayesian Search That Cut Latency 40%
Learn how to optimize RAG at scale using chunking, retrieval, and Bayesian search to reduce latency by 40%
Dev.to · Imus
📰
Optimizing RAG at Scale: Chunking, Retrieval, and the Bayesian Search That Cut Latency 40%
Learn how to optimize RAG at scale using chunking, retrieval, and Bayesian search to reduce latency by 40% and achieve 95% recall@10
Dev.to AI
📰
Optimizing RAG at Scale: Chunking, Retrieval, and the Bayesian Search That Cut Latency 40%
Learn how to optimize RAG at scale using chunking, retrieval, and Bayesian search to reduce latency by 40%
Dev.to · Imus
📰
Optimizing RAG at Scale: Chunking, Retrieval, and the Bayesian Search That Cut Latency 40%
Optimize RAG at scale using chunking, retrieval, and Bayesian search to reduce latency by 40% and achieve 95% recall@10
Dev.to AI

Chapters (17)

Introduction
0:20 What is R?
1:56 hello.R
7:39 Functions in R
12:49 readline
19:12 paste
29:08 Function Composition
34:19 count.R
39:36 Storage Modes
45:22 Tables
49:48 tabulate.R
55:50 Data Frames
1:01:48 Vectors
1:14:54 write.csv
1:17:49 voters.R
1:26:14 Special Values
1:30:35 Factors
Up next
Build a Chatbot with RAG in 10 minutes | Python, LangChain, OpenAI
Thomas Janssen
Watch →