In R, I have a loop. I would like to subset a dataframe by the variable in the loop. I would like my code to look like this:
library(maptools)
for(theMonth in 600: 0)
{
Inspections.mp <- readShapeLines("InspDates2")
counties.mp <- readShapePoly("Boundary")
plot(counties.mp, axes=FALSE, border="gray")
data1 <-Inspections.mp[Inspections.mp$MonthInt == theMonth]
lines(data1, col="blue", lwd=1)
}
Unfortunately, this returns all of the records in data1, and using the line
data1 <-Inspections.mp[Inspections.mp$MonthInt == theMonth,]
causes the following error: Error in bb[1, ] : incorrect number of dimensions
I can, however, get the records I want when just using a constant integer, but I need a variable
library(maptools)
for(theMonth in 600: 0)
{
Inspections.mp <- readShapeLines("InspDates2")
counties.mp <- readShapePoly("Boundary")
plot(counties.mp, axes=FALSE, border="gray")
data1 <-Inspections.mp[Inspections.mp$MonthInt == 60,]
lines(data1, col="blue", lwd=1)
}
The problem here seems to be a null subset. This is avoided by using a try/catch statement.
library(maptools)
Inspections.mp <- readShapeLines("InspDates2")
counties.mp <- readShapePoly("Boundary")
for(theMonth in 600: 0)
{
plot(counties.mp, axes=FALSE, border="gray")
result <- tryCatch({
data1 <-Inspections.mp[Inspections.mp$MonthInt == theMonth,]
lines(data1, col="blue", lwd=1)
},warning = function(war){
print("WARNING")
},error = function (err)
{
print("Error")
}, finally = {
print("Finally")
})
}