0

I try to concatenate a variable name by a string and a variable value to call an existing variable which I can use in further procedures, f.e.

var_pre23 <- "it works" # existing variable

var_pre <- "var_pre"
var_add <- 23
var_comb <- paste0 (var_pre, var_add) # results in "var_pre23"

print (var_comb) # this should lead to printing "it works"

I want to concatenate "var_add" and "var_pre" to a variable "var_pre23". The real variable "var_pre23" already exists and has the value "it works". So in the end I want to use

print(var_comb)

and receive the value "it works".

I know that from other script languages - as far as I remember in PHP it works like

echo ${"var_pre23"} or ${$var_pre.$var_add}

I think I only need a specific command for that.

Thank you!!

MDStat
  • 355
  • 2
  • 17
  • 1
    [Getting strings recognized as variable names in R](https://stackoverflow.com/questions/9057006/getting-strings-recognized-as-variable-names-in-r) – Henrik Jul 08 '21 at 10:41

2 Answers2

0

You have to use the function get to obtain the value :

var_pre23 <- "it works" 
var_pre <- "var_pre"
var_add <- 23
var_comb <- get(paste0(var_pre, var_add)) 

print(var_comb)
   
Emmanuel Hamel
  • 1,769
  • 7
  • 19
  • I just now posted the solution I found (sorry, I didn't see that you also answered) Thank you very much! – MDStat Jul 08 '21 at 11:28
0

Thank you very much - I used the following code, that worked:

var_comb <- eval(parse(text = paste0 (var_pre, var_add)))

Bye

MDStat
  • 355
  • 2
  • 17