R Tutorial



R VARIABLES


Variables in R

Variables in R are used to store data values such as numbers, strings, or other types. You can think of a variable as a container that holds information which you can use and manipulate in your program.

How to Create Variables

You assign a value to a variable using the <- operator or the equal sign =. The assignment operator <- is more common in R.

# Assigning value 10 to variable x
x <- 10

# Assigning a text string to variable name
name <- "R Language"

# Using equal sign (also valid)
y = 20
  

Rules for Variable Names

  • Variable names can contain letters, numbers, dots (.), and underscores (_).
  • They must start with a letter or a dot, but if it starts with a dot, it cannot be followed by a number.
  • Variable names are case sensitive (myVar and myvar are different).
  • Avoid using R reserved keywords (like if, for, TRUE, etc.) as variable names.

Checking Variable Values

To see the value stored in a variable, simply type the variable name:

x
# Output: [1] 10

name
# Output: [1] "R Language"
  

Variable Types

R automatically assigns the data type based on the value assigned. Common types are:

  • Numeric: Numbers with or without decimals (10, 3.14)
  • Character: Text strings ("Hello")
  • Logical: Boolean values (TRUE, FALSE)
  • Integer: Whole numbers with an L suffix (5L)

Checking Variable Type

class(x)       # numeric
class(name)    # character
class(TRUE)    # logical
class(5L)      # integer
  

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review