How can I convert a string to variable name an assign some value to this variable? In R I use assign() function for this, but I was not able to find its equivalent in Julia.
No it’s not possible and you shouldn’t do it. Use a
You might want to look into metaprogramming.
or use a
Dict as @yuyichao suggests.
OR you can use simple function (metaprogramming):
## string to varname function, see ## https://groups.google.com/forum/#!topic/julia-dev/z-dyQ_jUgk8 function string_as_varname(s::AbstractString,v::Any) s=symbol(s) @eval (($s) = ($v)) end
If you only care about global variables then something similar to this will certainly work.
As @yuyichao pointed towards,
eval works in the global scope, so this may not work the way you think it would inside of a function.
Doing it as a macro seems to work correctly inside a function (i.e. variables are created only in the local scope):
macro string_as_varname_macro(s::AbstractString, v::Any) s = Symbol(s) esc(:($s = $v)) end function string_as_varname_function(s::AbstractString, v::Any) s = Symbol(s) @eval (($s) = ($v)) end function test() string_as_varname_function("a",2) @string_as_varname_macro("b",3) println("(a,b) = ($a,$b)") end test() isdefined(:a) && println("a = $a") isdefined(:b) && println("b = $b") nothing
(a,b) = (2,3) a = 2
I’ve only been working with Julia for a few weeks, so please explain if this has some unintended side effect.
Best way to create/assign variables based on strings
As @yuyichao suggested, you are almost certainly going about the wrong way to do something. If you explain a little more about what you are trying to do, we could probably suggest something better.
I don’t know why Aaron1488 wants to do this, but I have a use case.
When building large optimization models in JuMP, you will often want to assign values to model parameters using external files in spreadsheets. When your model contains complex equations, it really helps readibility and maintainability if you can write
parameter3D[a,b,c] in your equations instead of looking up parameters in a Dict like
I guess you could first read the external data into the Dict and then manually add local variable aliases for each parameter, but that gets verbose and messy when you have dozens of parameters.
I think using the macro to define local variables for parameters is the best solution, but I’m open to suggestions if someone has a better idea.
@unpack macro in https://github.com/mauro3/Parameters.jl can be useful.
You can also use the @with macro in DataFramesMeta
using DataFramesMeta a = Dict(:parameter1D => [1,2,3]) @with a begin :parameter1D.^2 end