'R - pass a global variable to a function, modify it and save

I'm trying to build a dynamic function utilizing eval,parse, or whatever works

Intention of a function: a value setter.

Parameter input: list, name of list item, value

Return: don't really care

Current code

#call fun_lsSetValue(state_list,selected,"dropdown")

fun_lsSetValue <- function(ls,name,value){
 pars <- as.list(match.call()[-1])
 element <- as.character(eval(expression(pars$name)))
 if(is.null(value))
  eval(parse(text="ls[[element]] <- ''"))
 else
  eval(parse(text="ls[[element]] <- value"))

#part that I need help, I need to assign ls to "state_list" without 
#having to hard coded it in this function
#I have tried everything I can think of like
#assign(deparse(substitute(ls)),ls,.GlobalEnv)
#state_list <<- ls works, but I want to be dynamic
}

The problem I found is I need to pass the value of a local variable "ls" to where it came from dynamically (state_list) I know a <- function(a,name,value) {... return(a)} work, but this syntax is really not my preference. Since I'm trying to learn if same thing can be done without the assign out side of function. Any advise would be helpful.



Solution 1:[1]

Even though this is a terrible idea in general, something like

fun_lsSetValue <- function(ls,name,value){
    lsname <- deparse(substitute(ls))
    name <- deparse(substitute(name))
    ls <- get(lsname, envir=globalenv())
    if(is.null(value)) {
        value<-''
    }
    ls[[name]]<-value
    assign(lsname, ls,envir=globalenv())
}

should work

a <- list(x=1)
fun_lsSetValue(a,x,3)
a
# $x
# [1] 3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrFlick