2.1 Declaring variables
Declaring a variable (or object) is simple in R, we just need to give it a name and the content for that variable. This can be done either directly in the console or in the editor window and saved as a script.
Remember that code entered into the console window will be executed immediately when you press the [Enter] key. But do not expect output for every line you enter, many R commands do not print anything to the screen. Code in the editor document will only be executed when you run the lines of commands or run the entire script.
Declare an variable
-
Enter the example code below into your RStudio interface. You can type it directly into the console and pressing the [Enter] key after each line or in the editor window.
- Which method are you using? console or editor?
- Did you get any output after executing line [1]?
-
If you entered above code in the console, click on the Environment tab in the top-right corner window. Do you see the value
x
listed? If you do not then try again (or select thex <- 42
line in your editor window and click on Run).-
Try other commands, e.g.
y <- 555
, do you see a new variabley
listed in the Environment tab?
-
Try other commands, e.g.
x <- 42
x
## [1] 42
print(x)
## [1] 42
Setting variable values and viewing variable contents
Command | Description |
---|---|
<- |
This marker is used to set a variable’s value. The more standard = operator will also work but they have different levels of precedence. As best practice it is better to use <- in R. |
# |
The hashmark at the start of a line is a way to comment your code. This directs R to ignore the rest of the current line. Commenting your good is very good practice and is also used lots to remove commands that you may use in debugging a more complex workflow. |
print() |
Is the print function which writes out the value of the variable. Simply typing the name of the variable will also write out the value contained within, as seen in the examples above: x and print(x) |