Search code examples
rparsingvariable-assignmentstanrstan

Assign vector component using string in R


I have a string, say "ti[123]", and a corresponding value, say 1.2 What is the command I should use in R to assign 1.2 to the 123rd position of vector ti ? I tried assign("ti[123]",1.2) but it creates a new variable with name ti[123], which is not what I expected.

The reason I need to do this is that I use rstan's optimizing function to optimize a model, and it returns a named vector, with names like this (if you happen to use vectors of parameters in your model).


Solution

  • We can extract the number from the string using str_extract and assign the value

    library(stringr)
    assign('ti', '[[<-'(ti, as.numeric(str_extract("ti[123]",
                      '(?<=\\[)\\d+')), 1.2))
    

    Or

    ti[as.numeric(str_extract("ti[123]", '(?<=\\[)\\d+'))] <- 1.2
    

    Another option would be rm_square from library(qdapRegex) to extract the numbers

    library(qdapRegex) 
    ti[as.numeric(rm_square('ti[123]', extract=TRUE))] <- 1.2
    

    Update

    If we don't know the object name,

    str1 <- 'ti[123]'
    v1 <- strsplit(str1, '[][]')[[1]]
    assign(v1[1], `[[<-`(get(v1[1]), as.numeric(v1[2]), 1.2))
    get(v1[1])[123]
    #[1] 1.2
    

    Or

    ti[123]
    #[1] 1.2