[R] looping over a string

Greg Snow Greg.Snow at imail.org
Thu Jan 22 21:11:04 CET 2009


I don't see right off why the one works and the other doesn't, but this looks like one of those cases that would be better done using a list rather than global variables.

Instead of assigning the variables in the global workspace, create a list and assign them there.  Then you can use lapply instead of a loop and you avoid the potential pitfalls associated with globals.

Hope this helps,

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Thomas Schwander
> Sent: Thursday, January 22, 2009 12:38 PM
> To: r-help at r-project.org
> Subject: [R] looping over a string
> 
> Hi list,
> 
> I'm using R 2.8.1 under Windows vista. I have the following problem:
> 
> First of all I create a string-vector. Then I "convert" these strings
> into variables and assign a vector of numeric values. So far
> everything's fine.
> Now I want to do nearly the same again: I create another string-vector
> and I want to assign the variance. So I have to loop over the first
> string-vector.
> But this does not work unfortunately. I looked in the R-list-search but
> I cannot find the right answer.
> 
> Please find enclosed the pseudo-code:
> 
> #Tage zwischen berechnung und 31.03.2009
> Berechnung<-as.Date("22.01.2009","%d.%m.%Y")
> Enddatum<-as.Date("31.03.2009","%d.%m.%Y")
> Tage<-difftime(Enddatum, Berechnung)
> Tage<-as.numeric(substr(format(Tage),1,2))
> 
> #maximal interessierend sind 100 Tage (4 Monate)-Differenzen
> max_int<-82
> Tage<-max_int
> max_bob<-82
> 
> varnames<-paste("st_rendite_",seq(max_int),sep="")
> analyse<-rnorm(10000)
> for(i in 1:min(max_bob,max_int)){
>   assign(varnames[i],diff(log(analyse),i)*100)
> }
> 
> #Wurzel_t - Approximation überprüfen
> varianzen<-paste("var_",seq(Tage),sep="")
> for(i in 1:Tage){
> #in this line is the error I cannot handle (st_rendite_i):
>   assign(varianzen[i],var(st_rendite_i)/100^2)
> }
> 
> Thanks for your help,
> Thomas
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-
> guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list