rfor-loopindexing

Can the index name in a `for` loop be pulled from an environment variable?


Bit of a crazy question, but I'm just wondering. Suppose, I have a for loop inside some function, but I want to specify the index name when I run the function. In this example, I could set idxname <- 'ja' or idxname <- 'jb' . What I want to happen is that whichever input I choose will override the default value for that name set in the called otherfunc() .

##edit: perhaps a simpler example will show what I want. Suppose for some absurd reason you have a function like:

byTwo <- function(jdex, y) jdex*y   

and that you don't know a priori that the first argument is "jdex" . Then run this:

foo <- function(jname){
x <- vector()
for(jname in 1:5 ) x[jname] <- byTwo(jdex, 4)
}

What will happen here is that the inner function byTwo will halt with error "jdex not found" because the for-loop is using index "jname" I want to be able to execute foo('jdex') and have "jdex" be the name of the loop index and thus useable as a numeric value just as in a regular loop. . So, is it possible for the actual name of the loop index to be generated and "inserted" into the for or the do.call(``for``) code?

foo <- function(idxname){
x <- vector()
for(idxname in 1:5) x[idxname] <- otherfunc(ja=3, jb = 5) 
}

That is, if I call foo('ja'), then the internal call would be otherfunc(idxname, jb=5). I'm not saying this is a smart way to do anything, just wondering what sort of manipulations, if any, the R language will allow inside the parentheses of for(...)


Solution

  • I don't understand the purpose. Usually I'd say this is an xy problem.

    just wondering what sort of manipulations, if any, the R language will allow inside the parentheses of for(...)

    You can call the `for` function with do.call.

    #rm(list = ls())
    idx <- as.name("i")
    do.call(`for`, list(idx, 
                        1:2, 
                        quote(print(ls()))))
    #[1] "i"   "idx"
    #[1] "i"   "idx"
    

    As you see, this used i as the name for the index variable and that name is defined programmatically.

    whichever input I choose will override the default value for that name set in the called otherfunc()

    That sounds like you simply want some do.call(otherfunc, setNames(list(...), idxname)) construct.