[R] Create a list object in a loop

Aurelie Cosandey Godin GodinA at Dal.Ca
Fri Mar 9 17:16:00 CET 2012


Thank you very much Michael!
Best,
Aurelie

On 2012-03-09, at 11:56 AM, R. Michael Weylandt wrote:

> You are overriding "b" at each loop iteration and consequently only
> keeping the last one.
> 
> Perhaps
> 
> b <- list()
> 
> for(i in sort(unique(OT1$month))){
>     a<-OT1[OT1$month==i,]
>     b[[i]]<-ppp(a$longitude,a$latitude,marks=a$fTSUM,window=newW)
>     plot(b[[i]],main=i)
>   }
> 
> Generally it's bad practice to have a dynamically growing object in R
> but I think the performance penalty for lists isn't too bad. (Not
> verified, I just think I saw that somewhere)
> 
> What might be even better:
> 
> months <- sort(unique(OT1$month))
> 
> b <- vector("list", length(months))
> names(b) <- months
> 
> for(i in months){
>     a<-OT1[OT1$month==i,]
>     b[[i]]<-ppp(a$longitude,a$latitude,marks=a$fTSUM,window=newW)
>     plot(b[[i]],main=i)
>   }
> 
> Michael
> 
> On Fri, Mar 9, 2012 at 10:48 AM, Aurelie Cosandey Godin <GodinA at dal.ca> wrote:
>> Dear all,
>> 
>> I'm trying to create a list of point patterns ppp.object {spatstat} in a loop.
>> My dataset looks like this:
>> 
>>    > names(OT1);head(OT1);dim(OT1)
>>    [1] "EID"       "latitude"  "longitude" "month"     "year"      "CPUE"      "TSUM"
>>    [8] "fTSUM"
>>                    EID latitude longitude month year CPUE TSUM fTSUM
>>    1   167-1-1996-1135 67.70000 -61.81667     9 1996    0    0     F
>>    2  167-10-1996-1135 67.71667 -59.18333     9 1996    0    0     F
>>    3 167-100-1996-1135 67.86667 -59.43333    10 1996    0    0     F
>>    4 167-101-1996-1135 67.95000 -59.58333    10 1996    0    0     F
>>    5 167-102-1996-1135 68.10000 -59.76667    10 1996    0    0     F
>>    6 167-103-1996-1135 67.81667 -59.38333    10 1996    0    0     F
>>    [1] 2707    8
>> 
>> What I would like to do is to select data for each of my month and create a ppp.object.
>> 
>>    > sort(unique(OT1$month))
>>    [1]  7  8  9 10 11 12
>> 
>> The following loop works and I can see each of my figures:
>> 
>>    for(i in sort(unique(OT1$month))){
>>      a<-OT1[OT1$month==i,]
>>      b<-ppp(a$longitude,a$latitude,marks=a$fTSUM,window=newW)
>>      plot(b,main=i)
>>    }
>> 
>> How can I access each of my ppp.objects? I've tried adding a list() in the loop command such that I can access the data but without any success... Any help would be much appreciated!
>> 
>> Thank you!
>> ______________________________________________
>> 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