-
Notifications
You must be signed in to change notification settings - Fork 0
/
IMD_D1_M2_Lets_Start_Coding.Rmd
41 lines (26 loc) · 2.65 KB
/
IMD_D1_M2_Lets_Start_Coding.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#### Let's start coding
First we need to create a new R script file. Make sure you are working in the `imd-r-training-intro` project that you just created. Click on the **New File** icon ![new file icon](images/NewFile.PNG) in the top left corner. In the dropdown, select **R Script**. The source pane will appear with an untitled empty script. Go ahead and save it by clicking the **Save** icon (and make sure the **Source on Save** checkbox is deselected). Call it `my_first_script.R`.
##### The basics
We'll start with something simple. Basic math in R is pretty straightforward and the syntax is similar to simply using a graphing calculator. Try it out! You can use the examples below or come up with your own. Even if you're using the examples, try to actually type the code instead of copy-pasting - you’ll learn to code faster that way.
To run a single line of code in your script, place your cursor anywhere in that line and press CTRL+ENTER (or click the **Run** button in the top right of the script pane). To run multiple lines of code, highlight the lines you want to run and hit CTRL+ENTER or click **Run**.
Text following a hashtag/pound sign (#) will be ignored - use this to leave comments about what your code is doing. Commenting your code is one of the best habits you can form, and you should start now! Comments are a gift to your future self and anyone else who tries to use your code.
```{r ExecutingCode}
# By using this hashtag/pound sign, you are telling R to ignore the text afterwards. This is useful for leaving annotation of notes or instructions for yourself, or someone else using your code
# try this line to generate some basic text and become familiar with where results will appear:
print("Hello, lets do some basic math. Results of operations will appear here")
# one plus one
1+1
# two times three, divided by four
(2*3)/4
# basic mathematical and trigonometric functions are fairly similar to what they would be in excel
# calculate the square root of 9
sqrt(9)
# calculate the cube root of 8 (remember that x^(1/n) gives you the nth root of x)
8^(1/3)
# get the cosine of 180 degrees - note that trig functions in R expect angles in radians
# also note that pi is a built-in constant in R
cos(pi)
# calculate 5 to the tenth power
5^10
```
Notice that when you run a line of code, the code and the result appear in the console. You can also type code directly into the console, but it won't be saved anywhere. As you get more comfortable with R, it can be helpful to use the console as a "scratchpad" for experimenting and troubleshooting. For now, it's best to err on the side of saving your code as a script so that you don't accidentally lose useful work.