R Tutorial menu

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

r
"Welcome to R"
print(50 * 3)
Output
[1] "Welcome to R"
[1] 150

Comments

A comment starts with #. R ignores everything after it on that line.

Example

r
# Calculate the price of 4 notebooks
4 * 120   # each notebook costs Rs 120
Output
[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

r
name <- "Ayesha"
age <- 20
fee <- 15000
name
age + 1
Output
[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

RuleAllowedNot allowed
Start with a letter (or a dot not followed by a digit)total, .temp2total, _total
Use letters, digits, dots and underscorestotal_fee, total.feetotal-fee
Case sensitiveAge and age are different
Not a reserved wordmy_ifif, TRUE, function

R programmers often write names in lowercase with underscores, like monthly_sales.

Changing and Removing Variables

Example

r
balance <- 500
balance <- balance + 250
balance
rm(balance)
exists("balance")
Output
[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

r
city <- "Karachi"
temp <- 34
paste("Today in", city, "it is", temp, "degrees")
paste0("Roll-", 101)
Output
[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

r
item <- "Shirt"
price <- 1800
cat("The", item, "costs Rs", price, "\n")
Output
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

r
x <- 10; y <- 4
x %% y
Output
[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?

Learn R with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp