How to access a variable name dynamically (after creating variable name dynamically) in r

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`
}

I have tried different methods but getting errors. Like

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`
}

Error

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

Another approach

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`
}

Error

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

Any idea, how can I do this?



from Recent Questions - Stack Overflow https://ift.tt/3d8ZjzT
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)