0
0
R-programmingHow-ToBeginner · 3 min read

How to Declare Variable in R: Simple Syntax and Examples

In R, you declare a variable by assigning a value to a name using the <- operator or the = sign, like x <- 5 or y = "hello". This creates a variable named x or y that stores the assigned value.
📐

Syntax

To declare a variable in R, use a name followed by an assignment operator and a value. The two common assignment operators are <- and =. The variable name should start with a letter or a dot (not followed by a number) and can contain letters, numbers, dots, or underscores.

  • Variable name: The name you choose for your variable.
  • Assignment operator: Use <- (preferred) or = to assign a value.
  • Value: The data you want to store (number, text, vector, etc.).
r
variable_name <- value
variable_name = value
💻

Example

This example shows how to declare variables with different types of values: a number, text, and a vector. It also prints the variables to show their values.

r
x <- 10
name = "Alice"
numbers <- c(1, 2, 3, 4)

print(x)
print(name)
print(numbers)
Output
[1] 10 [1] "Alice" [1] 1 2 3 4
⚠️

Common Pitfalls

Some common mistakes when declaring variables in R include:

  • Using invalid variable names (starting with a number or special character).
  • Confusing the assignment operator <- with the comparison operator ==.
  • Overwriting important built-in function names.

Here is an example showing wrong and right ways:

r
# Wrong: variable name starts with a number
# 1var <- 5  # This will cause an error

# Wrong: using comparison instead of assignment
x == 5  # This checks if x equals 5, does not assign

# Right: valid variable name and assignment
var1 <- 5
x <- 5
📊

Quick Reference

ConceptExampleNotes
Assign numberx <- 10Stores number 10 in x
Assign textname = "Bob"Stores text in name
Assign vectorv <- c(1,2,3)Stores a vector of numbers
Invalid name2var <- 5Variable names cannot start with numbers
Comparison mistakex == 5Checks equality, does not assign

Key Takeaways

Use <- or = to assign values to variables in R.
Variable names must start with a letter and contain letters, numbers, dots, or underscores.
Avoid using reserved function names as variable names.
Remember that == is for comparison, not assignment.
Print variables to check their stored values.