# install packages
install.packages("sp")
install.packages("maps")
install.packages("maptools")
# load libraries
library(sp)
library(maps)
library(maptools)
# generate australia map from maps package
australia_map <- map("world", "Australia", fill = TRUE, plot = FALSE)
#convert to polygon using maptools package
australia_polygon <- map2SpatialPolygons(australia_map, IDs = australia_map$names, proj4string = CRS("+proj=longlat +datum=WGS84"))
# define points
points <- data.frame(x = c(151, 150, 100, 147), y = c(-33, 125, -20, -42))
# Create a logical vector to store the results for each point
within_polygon <- logical(nrow(points))
# Iterate over each polygon
for (i in 1:length(polygons)) {
# Extract the coordinates of the current polygon
polygon_coords <- australia_polygon@polygons[[i]]@Polygons[[1]]@coords
# Check if each point is within the current polygon
within_polygon <- within_polygon | sapply(1:nrow(points), function(j) {
point.in.polygon(points$x[j], points$y[j], polygon_coords[,1], polygon_coords[,2])
})}
within_polygon