massinissa
massinissa

Reputation: 952

How to turn variable values to variable names?

I have series of variables and values :

var1<- "MyVar1"
var2<- "MyVar2"
...
varN<- "MyVarN"

values1 <- c("a","b", "c")
values2 <- c("d","e", "f", "g")
...
valuesN <- c(...) 

The number N and the values of varX and valuesX are known at runtime (supplied by the user).

I need to turn them into a function parameter such as:

globalvar = list(MyVar1=c("a","b", "c"), MyVar2=c("d","e", "f", "g"), ... varN=c(...))

and then supply it to the function myfunction():

myfunction(globalvar = list(MyVar1=c("a","b", "c"), MyVar2=c("d","e", "f", "g"), ... varN=c(...)), other_parameters)

Upvotes: 1

Views: 102

Answers (3)

Konrad Rudolph
Konrad Rudolph

Reputation: 546133

Here’s a more concise way of doing this:

# Helper function to extract values / names
read <- function (prefix) function (i) get(paste0(prefix, i))

# Collect arguments
args <- setNames(lapply(1 : N, read('values')), lapply(1 : N, read('var')))

# Call function
myfunction(globalvar = args, other_parameters)

The argument collection still contains a slight repetition since we’re doing essentially the same for the values and their names but I think that’s permissible here, in particular since we’ve generalised their actual work into the read helper.

Notice also that your solution of using a separate environment isn’t actually necessary. You’re essentially just copying the variables from myListe into a new list tmp in a convoluted fashion.

Upvotes: 2

massinissa
massinissa

Reputation: 952

Finally I came up with this solution:

    myListe <- list()      
    for (i in 1:N) {
      var.name          <- get(paste("var",i,sep=""))
      var.values        <- get(paste("values",i,sep="")) 

      myListe[i]        <- list(var.values)
      names(myListe)[i] <- list(var.name)

    }

    tmp     <- new.env()  ; assign('globalvar',as.list(myListe),envir=tmp)

And then I call the function myfunction() as follows:

   do.call(myfunction, c(as.list(tmp),as.list(other_parameters)))

Is there a more concise way to do the same thing?

Upvotes: 0

James King
James King

Reputation: 6375

var3 <- list(values1, values2, ..., valuesN)
names(var3) <- c("MyVar1", "MyVar2", ... "MyVarN")

Upvotes: 1

Related Questions