R Variables
In this tutorial, we shall learn about R Variables, how to assign value to a variable, know the data type of variable, find the list of variables and delete some of them if required.
Variables are names given to storage locations of data. Once we declare that a variable would hold some specific data, we may access that specific data in the due course of the program using the variable name. In R programming language, any R-Object could be stored in a variable with a name given to the variable.
In R, a variable name is usually bound to an object in an environment. The object may be a number, character string, vector, list, data frame, function or any other R object. For day-to-day R programming, the most common tasks are assigning objects to names, checking what objects exist, inspecting their type and removing objects that are no longer needed.
Valid R variable names and naming rules
Following are the rules to give a valid name to an R variable.
- It may contain letters (Examples : x, y, varx, .. )
- It may contain numbers (Examples : x1, y1, var25x, .. )
- It may contain special char Dot (.) (Examples : x., y., var.x, .. )
- It may contain special char Underscore(_) (Examples : x_1, y_2, var_x, .. )
- The first character in the name could be a letter. (Examples : x, y, varx, .. )
- The first character in the name could be a dot not followed by a number. (Examples : .x, .y, varx, .. )
- Reserved words in R could not be used for variables.
Examples for invalid variable names : .2x, er@t
Strictly speaking, tan is syntactically valid in R, but it is a poor variable name because tan() is also the name of a built-in function. Avoid using names that hide common functions such as c, mean, sum, data or tan. Names such as .2x and er@t are invalid as normal variable names because they do not follow R’s name syntax.
Reserved words that cannot be used as R variable names
R has reserved words that are part of the language syntax. These words should not be used as variable names.
if
else
repeat
while
function
for
in
next
break
TRUE
FALSE
NULL
Inf
NaN
NA
NA_integer_
NA_real_
NA_complex_
NA_character_
If you try to assign a value to a reserved word, R treats it as syntax instead of a normal object name. Choose descriptive names such as student_count, sales_total, customer_age or marks_vector.
Assign value to R Variable
R Variable can be assigned a value using one of the following three operators :
- Equal Operator =
- Leftward Operator <-
- Rightward Operator ->
In the following, we have examples for equal operator, leftward operator and rightward operator respectively.
> x = 'hello'
> print(x)
[1] "hello"
> x <- 'learn r' > print(x)
[1] "learn r"
> 'r programming language' -> x
> print(x)
[1] "r programming language"
The left assignment operator <- is widely used in R examples and scripts. The equal operator = also assigns values in many situations, but <- makes assignment easy to distinguish from argument matching inside function calls. The right assignment operator -> is valid but is less commonly used in regular scripts.
student_name <- "Anu"
marks <- c(82, 91, 76)
average_marks <- mean(marks)
print(student_name)
print(average_marks)
[1] "Anu"
[1] 83
Check the data type and structure of an R variable
After assigning a value, you can inspect the variable to understand what kind of object it stores. Use class() to check the object class, typeof() to check the underlying type, and str() to view the structure of vectors, lists and data frames.
x <- 25
name <- "Ravi"
scores <- c(80, 75, 90)
class(x)
typeof(name)
str(scores)
[1] "numeric"
[1] "character"
num [1:3] 80 75 90
Find all R Variables
When you are running commands in an R command prompt, the instance might get stacked up with lot of variables.
To find all R variables that are alive at a point in R command prompt or R script file, ls() is the command that returns a Character Vector.
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "fruits" "listX"
[7] "RGB" "r programming language" "v"
[10] "values" "x" "y"
> p = 36.89
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "fruits" "listX"
[7] "p" "RGB" "r programming language"
[10] "v" "values" "x"
[13] "y"
You may also see objects() used for the same purpose because it is an alias for ls(). By default, ls() lists objects in the current environment. To include hidden objects whose names begin with a dot, use all.names = TRUE.
ls()
objects()
ls(all.names = TRUE)
Delete an R Variable
rm(variable_name) deletes an R variable from the stack of variables in a running instance.
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "fruits" "listX"
[7] "p" "RGB" "r programming language"
[10] "v" "values" "x"
[13] "y"
> rm(fruits)
> ls()
[1] "a" "A" "dataX"
[4] "factorX" "listX" "p"
[7] "RGB" "r programming language" "v"
[10] "values" "x" "y"
The function remove() is the same as rm(). Use either function to delete one or more objects from the current R environment. After deletion, trying to print the removed variable results in an object-not-found error.
city <- "Hyderabad"
amount <- 2500
rm(city)
remove(amount)
Remove multiple R variables in one command
To delete more than one R variable, pass all variable names to rm(). This is useful when a script creates temporary objects that should be removed before the next step.
first_name <- "Kiran"
last_name <- "Rao"
temporary_total <- 150
rm(first_name, last_name, temporary_total)
If you already have the variable names as character strings, use the list argument of rm().
x <- 10
y <- 20
z <- 30
vars_to_delete <- c("x", "y")
rm(list = vars_to_delete)
Delete all variables from the R workspace
To delete all variables from the current R workspace, combine rm() with ls(). The expression ls() returns the object names, and rm(list = ...) removes those objects by name.
rm(list = ls())
To include hidden objects whose names begin with a dot, use all.names = TRUE.
rm(list = ls(all.names = TRUE))
Use this command carefully in an interactive session. It removes objects from the current environment, so save important objects to a file before clearing the workspace.
Remove selected R variables by pattern
When variable names follow a pattern, use the pattern argument of ls() and pass the result to rm(). This avoids typing every temporary variable name manually.
temp_a <- 1
temp_b <- 2
final_value <- 3
rm(list = ls(pattern = "^temp_"))
In this example, only variables whose names start with temp_ are removed. The variable final_value remains available.
Keep selected R variables and delete the rest
Sometimes you may want to clear the workspace but keep one or two important objects. Use setdiff() to remove every object except the names that must be retained.
sales_data <- data.frame(amount = c(100, 200, 300))
model_result <- "draft"
temp_value <- 999
rm(list = setdiff(ls(), c("sales_data", "model_result")))
After running the command, sales_data and model_result remain in the workspace, while other listed objects are removed.
R variables in the workspace versus columns in a data frame
Deleting an R variable from the workspace is different from deleting a column from a data frame. The command rm(x) removes the object named x from the current environment. It does not remove a column named x from an existing data frame.
students <- data.frame(
name = c("Anu", "Ravi"),
marks = c(88, 76),
section = c("A", "B")
)
students$section <- NULL
In the example above, the section column is removed from the students data frame, but the students object itself still exists in the workspace.
What everything() means in R variable selection
everything() is commonly used in tidyverse column-selection helpers, especially with functions such as select(). It selects all columns in a data frame within that selection context. It is not the command for deleting all variables from the R workspace. For clearing workspace variables, use rm(list = ls()).
# tidyverse-style column selection example
# Select all columns from a data frame
# library(dplyr)
# students %>% select(everything())
Common mistakes while naming, listing and deleting R variables
- Using a built-in function name as a variable: A name such as
meanortancan hide the function of the same name in your workspace. - Expecting
rm()to delete data frame columns:rm()removes objects from an environment, not columns inside a data frame. - Forgetting quotes with
rm(list = ...): Thelistargument expects character names such asc("x", "y"). - Clearing the workspace too early:
rm(list = ls())removes current objects, so save important results before running it. - Assuming hidden objects appear in
ls(): Usels(all.names = TRUE)when you also need names that start with a dot.
FAQs on R variables, ls(), rm() and everything()
How do you delete all variables in R?
Use rm(list = ls()) to delete all visible variables from the current R workspace. If you also want to include hidden objects whose names begin with a dot, use rm(list = ls(all.names = TRUE)).
How to remove a specific variable in R?
Use rm(variable_name). For example, if the variable is named score, run rm(score). You can also use remove(score), because remove() is an alias of rm().
How do I delete multiple variables in R?
Pass multiple object names to rm(), such as rm(x, y, z). If the names are stored as strings, use rm(list = c("x", "y", "z")).
What does ls() do for R variables?
ls() returns the names of objects available in the current environment. It is commonly used to list variables before removing selected objects with rm().
What is everything() in R?
everything() is a tidyselect helper used to select all columns in a data-frame selection context. It is not used to clear R workspace variables. To remove all workspace variables, use rm(list = ls()).
Editorial QA checklist for this R variables tutorial
- Confirm that R variable naming rules mention letters, numbers, dot, underscore and the restriction on the first character.
- Check that
tanis not described as a syntactically invalid name, but as a name to avoid because it hides a built-in function. - Verify that the article distinguishes workspace variables from data frame columns.
- Confirm that
rm(list = ls())is explained as deleting visible objects from the current workspace. - Check that
everything()is explained as a tidyselect column-selection helper, not as a workspace cleanup command.
R variables assignment and cleanup summary
In this R Tutorial, we have learnt about R Variables and to assign values to them, to find all R variables and to delete some of them if necessary. We also covered how to remove multiple variables, clear the current workspace, keep selected objects, and understand the difference between deleting workspace variables and deleting data frame columns.
TutorialKart.com