# Sample variable in the environment
<- 42
my_variable
# Using get() to retrieve the value
<- get("my_variable")
result result
[1] 42
Steven P. Sanderson II, MPH
August 1, 2023
Welcome, fellow programmers, to this exciting journey into the world of R functions! Today, we’ll explore four powerful functions: get()
, get0()
, dynGet()
, and mget()
. These functions may sound mysterious, but fear not; we’ll demystify them together and see how they can be incredibly handy tools in your R toolkit. So, let’s dive in!
The get()
function is a versatile and often overlooked gem in R. Its primary purpose is to retrieve the value of a variable stored in an environment by specifying its name as a character string. The syntax of the get()
function is straightforward:
Let’s say you have a variable named my_variable
stored somewhere in your R environment, and you want to access its value using the get()
function:
In the example above, we used get("my_variable")
to access the value of the variable my_variable
. The function returned the value 42
, which was stored in the variable.
The get0()
function is closely related to get()
, but it has a subtle difference. It allows for the passing of an error message via the ifnotfound
parameters. The syntax of get0()
is:
Let’s use the same variable my_variable
as before and see the difference between get()
and get0()
:
In this example, get0("my_var")
returned an error message as the variable was not found.
The dynGet()
function is similar to get()
, but it searches for the variable in a specified environment. The syntax is:
Consider a scenario where you have a variable named num
inside a custom environment, and you want to access it using dynGet()
:
In this example, we used dynGet("num", custom_env$num)
to access the value of the variable num
from the specified custom_env
environment. The function successfully retrieved the value 99
.
The mget()
function is a workhorse when you want to retrieve multiple variables at once. It takes a vector of variable names as input and returns a named list with the values. The syntax is:
Let’s say we have two variables, x
and y
, and we want to retrieve their values using mget()
:
In this example, we provided the vector c("x", "y")
to mget()
, and it returned a named list with the values of both variables x
and y
.
Congratulations on reaching the end of this blog post! We’ve covered four essential functions in R: get()
, get0()
, dynGet()
, and mget()
. These functions enable you to access variables and their values efficiently, whether they reside in the global environment or custom environments. We hope you found this information useful and encourage you to try them out in your R projects. Happy coding, and may your R programming journey be filled with success and joy!