Tuesday, September 4, 2018

Lesson 1: Writing Your First Program In R Using R-Studio

So, you're ready to write your first program in R!  I'm really excited for you!  R is my one of my favorite programming languages because once you get the hang of the syntax, it's very intuitive and very well supported by the community.  Many times answers to your questions can be found through a simple Google search or by visiting Stack Exchange.

As you may (or may not) know when first learning a programming language, the first program you typically write is "Hello, World!".  So, that is what we are going to do here next with R in R-Studio!

NOTE:  To run the code in R-Studio, you can put your cursor all the way to the left on the line of code you'd like to execute.  For example place your cursor to the left of the 'p' in the 'print' function and press "ctrl + enter" (Windows/Linux) or "command + enter" (Mac OSX).  This will run that line of code and display "Hello, World!" in the R-Studio console window.


STEP 1: USE PRINT FUNCTION TO DISPLAY A STRING

To display a text string variable in the R-Studio console, you can use the 'print' function.
print("Hello, World!")

STEP 2: ASSIGN A STRING TO A VARIABLE AND USE PRINT TO DISPLAY IT

Next, let's assign "Hello, World!" to a string variable and use the 'print' function to display it in the console.
x = "Hello, World!"
print(x)

STEP 3: ASSIGN TWO STRINGS TO TWO VARIABLES AND USE PASTE TO DISPLAY IT

Next we will use the 'paste' function to combine variables and strings and like print, it will display the result in the console.

x = "Hello, World"
y = "once again!"
paste(x,y, sep = " ")

STEP 4: LEARNING MORE ABOUT R FUNCTIONS

At any time during your R-Studio session you can display information about a given functions by preceding the function with a '?'. This will display helpful information about the function in the viewer on the right.
?print
?paste

STEP 5: SAVING YOUR SCRIPT

Only one more step.  Let's save that script you just created by clicking on "File" -> "Save As..." and let's name your script "R_Lesson1.R"  Click "Save".
Congratulations!  You've completed Lesson 1!

DOWNLOAD CODE
Here is the code from my GitHub gist "R Lesson 1 - First Program" in case you'd rather just copy and paste it and then play around with it.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.