Search code examples
robjectvariable-assignmentassignassignment-operator

R: Is it possible to pass data stored in an object to a new object using the paste0 function (or some analogous function)?


Sorry if this was already asked, I did a thorough search but could not find a similar example. Maybe I am not using the right words to describe what I am trying to achieve? I think this would be very easy to do. Any advice is appreciated!

The problem:

I am wondering if there is a way to pass data stored in an object to a new object using the paste0 function, or some analogous method, to facilitate passing data from a stored object to a new object based on substituting in part of the name of the original object using a third object that contains a string. I thought maybe there was an assignment operator that could do this (<<-, or the assign function) but these do not achieve what I am trying to do.

Here is a simplified example to illustrate what I am trying to do and what I have already tried:

set.seed(123)

# Create fake data for each day where data was collected (in reality these are maps)
## Day 1 through...
day1.thresh   <- rnorm(5)
day1.thresh

## ...day XXX
dayXXX.thresh  <- rnorm(5)
 
# Manually specify the day of interest
day <- 'day1'

# THESE DO NOT WORK:
# Assign a new name to a data object using the paste0 
## ...using the normal assignment operator
newObject1 <- paste0(day, ".thresh")
newObject1

## ...using the <<- operator 
newObject2 <<- paste0(day, ".thresh")
newObject2

## ...using assign()
assign("newObject3", paste0(day, ".thresh"), inherits = T)
newObject3

Here's the output I get:

day1.thresh
>[1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774
newObject1
>[1] "day1.thresh"
newObject2
>[1] "day1.thresh"
newObject3
>[1] "day1.thresh"

Conclusions:

This approach obviously does not work. The name "day1.thresh" is assigned to the new object rather than passing the data associated with the day1 object to the newObject. Ideally, when I type newObject, the values stored in day1.thresh (-0.56047565, -0.23017749, 1.55870831, 0.07050839, 0.12928774) are returned instead of the name "day1.thresh".


Solution

  • You are looking for get :

    assign("newObject3", get(newObject1))
    newObject3
    #[1] -0.5605 -0.2302  1.5587  0.0705  0.1293