[R] recall variable in a loop

Jeff Newmiller jdnewmil at dcn.davis.CA.us
Sat May 10 15:54:39 CEST 2014


One answer to your question might be ?get. A way better answer is to never use assign to create xx1 etc in the first place but to store those results in a list that you can simply index later. If you were to create a reproducible example [1] by defining mydata you would be more likely to get an actual example solution in response to your question.

[1] http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example

---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                      Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k
--------------------------------------------------------------------------- 
Sent from my phone. Please excuse my brevity.

On May 10, 2014 2:07:29 AM PDT, Marco Chiapello <chiapello.m at gmail.com> wrote:
>I'd like to create several tables in which my data are stored.
>I did the follow:
>    
>    x<-mydata
>    splitted<-split(x[,1],x[,2])
>    
>    #Create my function for the tables
>    fxdata<-function(){
>    y.row=c("0","1","2","3","4","5")
>    yy=c(rep(0,6))
>    w=data.frame(A3=yy,A2=yy,A1=yy,A0=yy)
>    rownames(w)<-y.row}
>
>    #Create the tables
>    xx<-NULL
>    for (i in 1:dim(x)[2]){
>    assign(paste("xx",i,sep=""),fxdata())}
>
>So, I created, for example, 3 tables: xx1, xx2 and xx3. Now I have to
>populate the tables and here I have the problem. I do not know how to
>recall xx1, xx2 or xx3 in a loop. The idea is insert the follow loop in
>the previous one, in order to populate all the tables.
>
>     #Populate the table
>     for (ii in 1:length(splitted[[1]]{
>     #IF 0
>     if (splitted[[1]][ii] == "0"){
>     y[1,4]=y[1,4]+1}
>     #IF A0
>     if (splitted[[1]][ii] == "1A0"){
>     y[2,4]=y[2,4]+1}
>     if (splitted[[1]][ii] == "2A0"){
>     y[3,4]=y[3,4]+1}
>     if (splitted[[1]][ii] == "3A0"){
>     y[4,4]=y[4,4]+1}
>     ...}
>
>The question is: what I have to write in place of "y" in the last loop
>in order to refer to xx1, xx2 or xx3?? I want to write something like:
>   
>    for (i in 1:3) {
>    xxi<-1}
>
>Thank you for any advice.
>
>Marco
>______________________________________________
>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