Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list object in a loop in R

Tags:

loops

r

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)
}

I would like to create a list of all my ppp.object that I can access individually, I've tried adding a list() in the loop command but without any success... Any help would be much appreciated!

Thank you!

like image 361
GodinA Avatar asked Oct 20 '25 16:10

GodinA


1 Answers

This seems like a good fit for lapply:

pppList <- lapply(sort(unique(OT1$month)), function(i) {
  a<-OT1[OT1$month==i,]
  ppp(a$longitude,a$latitude,marks=a$fTSUM,window=newW)
})

...But just to explain how to fix you for-loop:

You need to have a list to assign to. And creating one of the correct length is always a good idea for performance:

x <- sort(unique(OT1$month))
pppList <- vector('list', length(x))
for(i in x) { 
  a<-OT1[OT1$month==i,]
  b<-ppp(a$longitude,a$latitude,marks=a$fTSUM,window=newW)
  pppList[[i]] <- b
  plot(b,main=i)
}
like image 97
Tommy Avatar answered Oct 23 '25 06:10

Tommy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!