[R] Treat Variable as String and a String as variables name

Berend Hasselman bhh at xs4all.nl
Sat Mar 10 11:19:45 CET 2012


On 10-03-2012, at 10:39, Alaios wrote:

> Dear all.
> I am having ten variables (let's call the four of them as 
> 
> Alpha, Beta, Gamma and Delta.....)
> 
> For each variable I have to print around 100 (plots). E
> 
> So far I was copying paste the code below many times. 
> 
> pdf(file="DC_Alpha_All.pdf", width=15) # First Variable is treated as string
> plot_dc_for_multiple_kapas(Alpha, 4, c(5, 4), coloridx=c(24, 32)) # First Variable is now passed #inside the function as variable
> dev.off()
> 
> So I could save my time If I can make a function that for every variable produces the current number of plots. The problem is, as you can also see from comment above that my variable has to be converted to string (first line) and also at the second line should be used as a variable.
> 
> How I can make a loop in R that for a list of variables (the 10 variables I gave at the beginning) can either treat each entry of that list once as a string and once a real variable.

Something like this

varlist <- LETTERS[1:10]
varlist

for( k in 1:length(varlist) ) assign(varlist[k], runif(10))
varlist

myplot <- function(x,k) plot(x,col=k)
for( k in 1:length(varlist) ) {    
    varname <- varlist[k]
    filename <- paste("DC_",varname,"_All.pdf", sep="")
    pdf(file=filename, width=15)
    myplot(get(varlist[k]),k)
    dev.off()
}

Berend



More information about the R-help mailing list