2

I'am using a shapefile with leaflet in r, where i am iterating through each row of that shapefile with a for loop and then i run an if statement on each of the rows as it iterates through the shapefile. My problem is that when I run it, it takes ages to iterate through and show the results. Is there any way to speed up my code?

R code:

# loop through each row of shapefile and run if statement on each row.
for(i in 1:nrow(shapeData)) {
  if(shapeData@data[i,]$TOTAL2011 > 400){

    m <- addPolygons(m, data=shapeData[i,],weight=1, popup = map_popup2, fillOpacity = 0.5,
                     color = "yellow") %>%
    print(m)

 }
} 
  • You could just subset your data to a new object first and avoid the iteration entirely. shapeData.sub <- shapeData[shapeData$TOTAL2011 < 400,] – Jeffrey Evans Apr 11 '17 at 16:46
  • @JeffreyEvans Ok i'll just use subset, its less hassle than iteration and is much more efficient, Thank you. – Elessar-1311 Apr 11 '17 at 21:47
1

I used Jeffery Evans answer shown above in the comments. In his answer he suggested I subset my data :

shapeData.sub <- shapeData[shapeData$TOTAL2011 < 400,]

This worked perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.