Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

R Basics: Values, Variables and Operators

Learn the building blocks of R code: arithmetic and comparison operators, assigning variables, naming rules, calling functions, comments and printing output.

Every R program is built from a few simple parts: values, names that hold them, operators that combine them and functions that transform them. In this lesson you will learn each part with small examples. Run them in your own R session as you read.

R as a calculator

R follows the usual order of operations. Brackets first, then powers, then multiplication and division, then addition and subtraction.

R
7 + 3 * 2
#> [1] 13

(7 + 3) * 2
#> [1] 20

2 ^ 10
#> [1] 1024

10 %% 3     # remainder (modulo)
#> [1] 1

10 %/% 3    # integer division
#> [1] 3

10 / 4
#> [1] 2.5
Operator Meaning Example Result
+ - * / Basic arithmetic 8 / 2 4
^ or ** Power 3 ^ 2 9
%% Remainder 17 %% 5 2
%/% Integer division 17 %/% 5 3

Special values appear when math breaks down:

R
1 / 0
#> [1] Inf

-1 / 0
#> [1] -Inf

0 / 0
#> [1] NaN

Inf is infinity and NaN means "not a number". R does not stop with an error here.

Variables and assignment

A variable is a name that points to a value. Create one with <-:

R
age <- 30
city <- "Nairobi"
is_student <- TRUE

age + 5
#> [1] 35

You can also assign with = or write the arrow the other way (30 -> age), but <- is the standard style. In RStudio, press Alt+minus to type <- quickly.

Assigning does not print anything. To see a value, type its name or call print():

R
age
#> [1] 30

Assigning again replaces the old value:

R
score <- 50
score <- score + 10
score
#> [1] 60

Naming rules

  • Names may contain letters, digits, dots and underscores.
  • They must not start with a digit or an underscore.
  • Names are case sensitive: total and Total are different variables.
  • You cannot use reserved words such as if, else, for, TRUE, NULL.

Good style is lowercase words joined by underscores, called snake_case: monthly_sales, first_name. Choose names that say what the value means. n_rows beats x1.

R
my_value <- 10    # fine
my.value <- 10    # valid (older style, used in many packages)
2nd_value <- 10   # Error: unexpected symbol

Comparison and logical operators

Comparisons produce TRUE or FALSE, called logical values.

R
5 > 3
#> [1] TRUE

5 == 5      # equal to (two equals signs!)
#> [1] TRUE

5 != 5      # not equal
#> [1] FALSE

"apple" < "banana"   # alphabetical comparison
#> [1] TRUE

= is not ==. A single = assigns, a double == compares. Writing if (x = 3) is an error in R, but confusing the two is a common slip when you are new.

Combine conditions with logical operators:

Operator Meaning
! NOT
& AND (element by element)
| OR (element by element)
&& AND for single values, stops early
|| OR for single values, stops early
R
age <- 30
age > 18 & age < 65
#> [1] TRUE

!(age > 18)
#> [1] FALSE

You will meet the difference between & and && properly in Conditionals.

Functions

A function takes input (arguments) and returns a result. You call it by writing its name followed by brackets.

R
sqrt(144)
#> [1] 12

round(3.14159, digits = 2)
#> [1] 3.14

max(4, 9, 2)
#> [1] 9

nchar("data")
#> [1] 4

Arguments can be given by position or by name. round(3.14159, 2) and round(3.14159, digits = 2) do the same thing. Names make code clearer and let you skip optional arguments. To see which arguments a function accepts, use args(round) or open its help page with ?round (see Help and Workflow).

Functions can be nested. R evaluates the inside first:

R
sqrt(abs(-16))
#> [1] 4

Useful built-in constants include pi (3.141593 when printed) and LETTERS (the capital letters A to Z).

Comments and printing

Comments explain the why of your code:

R
# Convert a Celsius temperature to Fahrenheit
celsius <- 25
fahrenheit <- celsius * 9 / 5 + 32
fahrenheit
#> [1] 77

To produce readable messages, combine cat() and paste():

R
name <- "Lena"
cat("Welcome,", name, "\n")
#> Welcome, Lena

message <- paste("Total:", 3 * 4)
print(message)
#> [1] "Total: 12"

paste() joins values into one string (with a space between by default). paste0() joins with no separator.

Seeing what you have

R
ls()            # names of your variables
rm(score)       # remove one variable
class(age)      # what kind of value is it?
#> [1] "numeric"

class() tells you the type of a value. You will explore types deeply in Data Types and Coercion.

Common mistakes

  1. Forgetting quotes around text: city <- Nairobi looks for a variable named Nairobi and fails.
  2. Wrong case: Print("x") fails because the function is print.
  3. Unbalanced brackets or quotes leave R waiting with a + prompt.
  4. Using = instead of == in comparisons.

Read error messages slowly. Error: object 'x' not found literally means R has no variable called x.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does 17 %% 5 return?

    %% is the remainder. 17 divided by 5 is 3 with remainder 2.
  2. 2. Which line assigns the value 10 to x in the standard R style?

    <- is the usual assignment operator. == only compares.
  3. 3. Which variable name is invalid?

    Names cannot start with a digit.
  4. 4. What does 0 / 0 give in R?

    R returns NaN (not a number) instead of stopping.

Summary

  • R evaluates arithmetic with the usual precedence; %% is remainder and %/% is integer division.
  • Create variables with <-; names are case sensitive and cannot start with a digit.
  • Comparisons (==, !=, <, >) return TRUE or FALSE; combine them with &, | and !.
  • Functions take arguments by position or by name and can be nested.
  • Use # for comments and cat()/print()/paste() for output.

Next: R Packages