R Variables

📦 R Variables

Variables in R are used to store data values so they can be reused and manipulated in a program.

🔹 1. Creating Variables in R

R mainly uses the assignment operator <-.

x <- 10
name <- "R Language"
price <- 99.5

✔ You can also use =, but <- is preferred.

y = 20

🔹 2. Rules for Variable Names

✔ Must start with a letter or dot (.)
✔ Can contain letters, numbers, underscore (_), dot (.)
❌ Cannot start with a number
❌ Cannot use R reserved keywords

age <- 25 # valid
.total <- 100 # valid
2value <- 10 # invalid
if <- 5 # invalid

🔹 3. Case Sensitivity

R is case-sensitive.

marks <- 80
Marks <- 90

marks and Marks are different variables


🔹 4. Types of Values Stored in Variables

a <- 10 # Numeric
b <- 10.5 # Decimal
c <- "Hello" # Character
d <- TRUE # Logical

R automatically detects the data type.


🔹 5. Printing Variable Values

x <- 50
print(x)
x

🔹 6. Multiple Variable Assignment

a <- b <- c <- 100

🔹 7. Variable Reassignment

x <- 10
x <- 20
print(x)

✔ Latest value replaces old value


🔹 8. Removing Variables

rm(x)

Remove multiple variables:

rm(a, b, c)

Remove all variables:

rm(list = ls())

🔹 9. Check Variable Type

x <- 10
class(x)

🔹 10. Best Practices for Variables

✔ Use meaningful names (total_marks, student_age)
✔ Use lowercase with underscore
✔ Avoid single-letter variables (except loops)


📌 Summary

  • Variables store data

  • <- is preferred assignment operator

  • R is case-sensitive

  • Variables can be reassigned

You may also like...