R - Variables
R - Variables
Section titled “R - Variables”A variable provides us with named storage that our programs can manipulate. In R, a variable can store a wide range of objects, from a single value (like a number) to a complex structure (like a data frame or model). A valid variable name consists of letters, numbers, the dot (.), and the underscore (_) characters. It must start with a letter or a dot, but if it starts with a dot, it cannot be immediately followed by a number.
Variable Naming Conventions and Validity
Section titled “Variable Naming Conventions and Validity”| Variable Name | Validity | Reason & Best Practice |
|---|---|---|
user_id | Valid | Recommended Style. Uses snake_case, which is preferred by the Tidyverse style guide. |
var.name | Valid | Technically valid, but not recommended. The . is used for S3 object-oriented programming in R and can cause confusion. |
var_name% | Invalid | Contains a special character (%). Only letters, numbers, . and _ are allowed. |
2_var_name | Invalid | Cannot start with a number. |
.internal_data | Valid | Can start with a dot. Such variables are ‘hidden’ by default from the ls() command. |
.2_var_name | Invalid | A dot at the start cannot be followed by a number. |
Variable Assignment
Section titled “Variable Assignment”The primary assignment operator in R is <-. While = can also be used for assignment in most cases, <- is the strong convention and is recommended to improve code clarity and avoid ambiguity with setting arguments in function calls. The rightward operator -> also exists but is rarely used.
# Best practice: Use the leftward arrow `<-` for assignment.var_1 <- c(0, 1, 2, 3)
# The equals sign `=` also works but is best reserved for function arguments.var_2 = c("learn", "R")
# The rightward arrow `->` is valid but unconventional.c(TRUE, 1) -> var_3
# Use the `print()` function for explicit output.print(var_1)
# The `cat()` function concatenates and prints, with `\n` for a new line.cat("Variable 1 is:", var_1, "\n")cat("Variable 2 is:", var_2, "\n")cat("Variable 3 is:", var_3, "\n")When we execute the above code, it produces the following result:
[1] 0 1 2 3Variable 1 is: 0 1 2 3Variable 2 is: learn RVariable 3 is: 1 1Note on Type Coercion: The vector c(TRUE, 1) contains both a logical and a numeric value. R coerces the values to the most flexible type, which in this case is numeric. Therefore, TRUE is converted to 1.
Dynamic Typing
Section titled “Dynamic Typing”R is a dynamically typed language. This means you don’t declare a variable’s data type in advance. A variable automatically takes on the data type of the object assigned to it, and you can change this type by reassigning a different object to it.
# Assign a character stringmy_variable <- "Hello, R!"cat("The class of my_variable is:", class(my_variable), "\n")
# Reassign a numeric (double precision) valuemy_variable <- 34.5cat("Now the class of my_variable is:", class(my_variable), "\n")
# Reassign an integer value (the 'L' suffix denotes integer)my_variable <- 27Lcat("Finally, the class becomes:", class(my_variable), "\n")When we execute the above code, it produces the following result:
The class of my_variable is: characterNow the class of my_variable is: numericFinally, the class becomes: integerManaging Variables in the Environment
Section titled “Managing Variables in the Environment”You can manage the variables in your current R session (the global environment) using a few key functions.
Listing Variables
Section titled “Listing Variables”The ls() function lists all visible variables. You can use the pattern argument to search for names, or all.names = TRUE to show hidden variables (those starting with a dot).
# Create some variables for demonstrationvar_a <- 1var_b <- "text".hidden_var <- TRUE
# List all visible variablesprint(ls())
# List variables matching a pattern (e.g., starting with 'var')print(ls(pattern = "^var"))
# List all variables, including hidden onesprint(ls(all.names = TRUE))Deleting Variables
Section titled “Deleting Variables”Use the rm() function to remove one or more variables from the environment. To clear your entire workspace, you can combine rm() and ls().
# Create a variable to deletedelete_me <- "I am temporary"print(exists("delete_me"))
# Remove the variablerm(delete_me)print(exists("delete_me"))
# To remove all variables from the environment:# This is a powerful command, use with care!rm(list = ls())print(ls())Best Practice: For a completely clean slate, it’s often better to restart your R session (In RStudio: Session > Restart R or Ctrl+Shift+F10). This ensures that loaded packages and other environment settings are also reset.