6.1 Write the classic "Hello, World!" example - Video Tutorials & Practice Problems
Video duration:
2m
Play a video:
Video transcript
<v Voiceover>This wouldn't be</v> a complete programming guide if it didn't include at least one Hello, World! example. We will build a function whose sole purpose is to print Hello, World! So to get started, it helps to understand a little bit about functions in R. They are treated just like every other variable. They are assigned to a variable, and can be passed around just like another variable. So, let's create a new variable called say.hello, and let's make it equal to a function, and we're going to say it takes no arguments. We'll build the body of the function, and it's good practice to encase the body of the function in curly braces. If it's a one-line function, they're not necessary, but anytime you get beyond one line, you need them there. Where you place the curly braces is open to debate. Some programmers like to putting it on the function declaration line; I prefer them on their own line. So in this function, we will just write, print, which is a function that prints to the screen, Hello, World! So this function, whenever it's called, it will simply print Hello, World! So we have to highlight the entire function and run the whole thing. You can see it went into the console, and now it's available to us. In fact, we type that function name in, and nothing else, we can see it prints out the whole function. Where it's a function with no arguments that just says print Hello, World! If we call that function, say.hello, open and close parentheses, it prints Hello, World!, so we can see here, say to hello successfully printed Hello, World! This function didn't take any arguments, so you call it, just open and close parentheses, and it prints out it's job. The important takeaways are that functions get assigned to variables. You declare a function by the keyword function, and if you have arguments, you put them inside the parentheses, as we will see a little bit later.