How to Use the get() Function in R to Retrieve Named Objects


You can use the get() function in R to retrieve named objects.

Here are the three most common get() functions in R:

1. get() – Retrieve one object

get("my_object")

2. get0() – Retrieve one object, using custom error message if not found

get0("my_object", ifnotfound="does not exist")

3. mget() – Retrieve multiple objects

mget(c("my_object1", "my_object2", "my_object3"))

The following examples show how to use each function in practice.

Example 1: Use get() to Retrieve One Object

The following code shows how to use the get() function to retrieve one name object:

#define vector of values
data1 <- c(4, 5, 5, 6, 13, 18, 19, 15, 12)

#get vector of values
get("data1")

[1]  4  5  5  6 13 18 19 15 12

If the named object does not exist, this function returns an error:

#define vector of values
data1 <- c(4, 5, 5, 6, 13, 18, 19, 15, 12)

#attempt to get vector of values
get("data0")

Error in get("data0") : object 'data0' not found

Example 2: Use get0() to Retrieve Object, Using Custom Error Message

We can also use the get0() function to retrieve a named object in R and use a custom error message if the object is not found:

#define vector of values
data1 <- c(4, 5, 5, 6, 13, 18, 19, 15, 12)

#attempt to get vector of values
get0("data0", ifnotfound="does not exist")

[1] "does not exist"

Since the named object “data0” does not exist, the get0() function returns the custom error message that we created.

Example 3: Use mget() to Retrieve Multiple Objects

We can use the mget() function to retrieve multiple named objects in R:

#define three vectors
data1 <- c(4, 5, 5, 6, 13, 18, 19, 15, 12)
data2 <- c("A", "B", "C", "D")
data3 <- c(10, 20, 25, 30, 35)

#get all three vectors
mget(c("data1", "data2", "data3"))

$data1
[1]  4  5  5  6 13 18 19 15 12

$data2
[1] "A" "B" "C" "D"

$data3
[1] 10 20 25 30 35

Note that if we just tried to use the get() function, only the first named object would be returned:

#define three vectors
data1 <- c(4, 5, 5, 6, 13, 18, 19, 15, 12)
data2 <- c("A", "B", "C", "D")
data3 <- c(10, 20, 25, 30, 35)

#attempt to get all three vectors
mget(c("data1", "data2", "data3"))

[1]  4  5  5  6 13 18 19 15 12

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use the c() Function in R
How to Use the sprintf() Function in R
How to Use the replace() Function in R

Leave a Reply

Your email address will not be published. Required fields are marked *