dugo dugo - 2 months ago 7
R Question

Using strings from loops as parts of function commands and variable names in R

How does one use the string coming from a loop
- to generate new variables

- as a part of functions commands

- as functions' arguments

- as a part of if statements

in R?

Specifically, as an example (the code obviously doesn't work, but I'd like to have something not less intelligible than what is bellow),

list_dist <- c("unif","norm")
for (dist in list_dist){
paste("rv",dist,sep="") = paste("r",dist,sep="")(100,0,1)
paste("meanrv",dist,sep="") = mean(paste("rv",dist,sep=""))
if (round(paste("meanrv",dist,sep=""),3) != 0){
print("Not small enough")
}
}


Note: This is an example and I do need to use kind of loops to avoid writing huge scripts.




I managed to use strings as in the example above but only with eval/parse/text/paste and combining the whole statement (i.e. the whole "line") inside paste, instead of pasting only in the varname part or the function part, which makes code ugly and illegible and coding inefficient.

Other available replies to similar questions which I've seen are not specific as in how to deal with this sort of usage of strings from loops.

I'm sure there must be a more efficient and flexible way to deal with this, as there is in some other languages.

Thanks in advance!

Answer

try this:

list_dist <- list(unif = runif,norm = rnorm)
for (i in 1:length(list_dist)){
    assign(paste("rv",names(list_dist)[i],sep=""), list_dist[[i]](100,0,1))
    assign(paste("meanrv",names(list_dist)[i],sep=""),mean(get(paste("rv",names(list_dist)[i],sep=""))))
    if (round(get(paste("meanrv",names(list_dist)[i],sep="")),3) != 0){
        print("Not small enough")
    }
}
Comments