R Syntax and Variables
This lesson covers the basic rules of R code: printing, comments and variables.
Printing Output
In the console, R shows the value of an expression automatically. Inside functions and loops, use print():
Example
"Welcome to R"
print(50 * 3)[1] "Welcome to R" [1] 150
Comments
A comment starts with #. R ignores everything after it on that line.
Example
# Calculate the price of 4 notebooks
4 * 120 # each notebook costs Rs 120[1] 480
R has no special multi-line comment. Simply start each line with #. In RStudio, select several lines and press Ctrl + Shift + C to comment them all at once.
Creating Variables
In R, the usual way to give a value to a variable is the arrow <-:
Example
name <- "Ayesha"
age <- 20
fee <- 15000
name
age + 1[1] "Ayesha" [1] 21
You can also use =, and it works the same in most places. But <- is the standard style in R, so you will see it everywhere.
In RStudio, press Alt + - (Alt and the minus key) to type <- quickly.
Naming Rules
| Rule | Allowed | Not allowed |
|---|---|---|
| Start with a letter (or a dot not followed by a digit) | total, .temp | 2total, _total |
| Use letters, digits, dots and underscores | total_fee, total.fee | total-fee |
| Case sensitive | Age and age are different | |
| Not a reserved word | my_if | if, TRUE, function |
R programmers often write names in lowercase with underscores, like monthly_sales.
Changing and Removing Variables
Example
balance <- 500
balance <- balance + 250
balance
rm(balance)
exists("balance")[1] 750 [1] FALSE
rm() removes a variable. ls() lists all the variables you have created.
Joining Text
paste() joins values with a space between them. paste0() joins without a space.
Example
city <- "Karachi"
temp <- 34
paste("Today in", city, "it is", temp, "degrees")
paste0("Roll-", 101)[1] "Today in Karachi it is 34 degrees" [1] "Roll-101"
cat() prints text without quotes and without [1]. Add "\n" for a new line:
Example
item <- "Shirt"
price <- 1800
cat("The", item, "costs Rs", price, "\n")The Shirt costs Rs 1800
Several Statements on One Line
Normally you write one statement per line. To put two on one line, separate them with a semicolon:
Example
x <- 10; y <- 4
x %% y[1] 2
%% gives the remainder after division. You will learn more operators in the next lesson.
Exercise
Exercise
Which is the standard way to assign the value 5 to x in R?
