David Lee David Lee - 8 days ago 5
R Question

Assign a value to character named variable with index

I know we can use

assign
to assign values to a character name vector. For example

assign("target",1:5)


However, if we want to change the 1st element of the
target
(
target
can be a vector/matrix/list), how should we do that?
target
here can also be a matrix, so we can change one element, one row or one column.
I want to do something like

target[1] <- 99


if I use

assign("target[1]",99)


it will only generate a new object named
target[1]
and value is 99. Here is a simple and trial example

# This function is meaningless, just used to show my situation
# variable_name is a character
example_function <- function(variable_name){
assign(variable_name,1:5)

if(rnorm(1)>1){
variable_name[1] <- 99 #This will not work and I just need some function to achive this purpose
}
}
example_function("justAname")

Answer

As an alternative approach you could use the [<- function.

f = function(variable_name){
  assign(variable_name,1:5)
  if(rnorm(1)>1){
    `[<-`(eval(as.name(variable_name)),i = 1, value = 99)
  }
  get(variable_name)
}

This should also work with matrices

f_mat = function(variable_name){
  assign(variable_name,matrix(1:25,nrow = 5))
  if(rnorm(1)>1){
    `[<-`(eval(as.name(variable_name)),i = 1, j = , value = 99) # for 1st row
    # `[<-`(eval(as.name(variable_name)),i = , j = 1, value = 99) # for 1st col
    #specify i and j for ith row jth column
  }
  get(variable_name)
}

and lists similarly.