How to get variable names dynamically (after creating the variable dynamically)

I want to create some variable names dynamically. After creation the variable name, I also want to use them.

For example, I want to create a variable name dynamically x_1 (at the time of i=1) and after create, I want to use this (x_1) in the next line.

threshold <- 0.5
length <- 2

for (i in 1:3) {
  assign(paste('x', i, sep='_'), 1)
  assign(paste('y', i, sep='_'), x + (threshold * 0.2) - (length - 1.3)) // here I want the name (and value) of the `x` based on `i`
  assign(paste('z', i, sep='_'), y * i + 2) // // here I want the name (and value) of the `y` based on `i`
}

Can you give me any idea?
Thank you

It may be better to allocate x_1 within an object rather than as an object

assign ( paste0("DataThing$x_", i), 1)
DataThing[paste0("x_", i)]

but

eval(paste0("x_", i ))

Should do it

@CALUM_POLWART Do you mean something like this?

threshold <- 0.5
length <- 2

for (i in 1:3) {
  assign(paste('x', i, sep='_'), 1)
  assign(paste('y', i, sep='_'), eval(paste0("x_", i) + (threshold * 0.2) - (length - 1.3))) # here I want the name (and value) of the `x` based on `i`
  assign(paste('z', i, sep='_'), eval(paste0("y_", i) * i + 2)) # here I want the name (and value) of the `y` based on `i`
}

But I am getting the error

Error in paste0("x_", i) + (threshold * 0.2) : 
  non-numeric argument to binary operator

I also tried this idea

for (i in 1:3) {
  assign(paste0("DataThing$x_", i), 1)
  assign(paste0("DataThing$y_", i), DataThing[paste0("x_", i)] + (threshold * 0.2) - (length - 1.3)) # here I want the name (and value) of the `x` based on `i`
  assign(paste0("DataThing$y_", i), DataThing[paste0("y_", i)] * i + 2) # here I want the name (and value) of the `y` based on `i`
}

But getting error

Error in assign(paste0("DataThing$y_", i), DataThing[paste0("x_", i)] +  : 
  object 'DataThing' not found

Solution

threshold <- 0.5
path_length <- 2

for (i in 1:3) {
  assign(paste('x', i, sep='_'), 1)
  assign(paste('y', i, sep='_'), get(eval(paste0("x_", i, sep=""))) + (threshold * 0.2) - (path_length - 1.3)) 
  assign(paste('z', i, sep='_'), get(eval(paste0("y_", i, sep=""))) * i + 2)
}
1 Like

If you want to access an object by string, just use get. For more than one object, mget. There is no need of eval for this purpose.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.