0

I originally tried to write this with a for-loop, and after trying it multiple ways it just wasn't working. Does anyone have suggestions for writing a for-loop for the col1-col15 part or any other recommendations on how to tidy up this code?

It's designed to generate a list of lat/lon points in grid form. Eventually, I take each point and pass it through an API to get a 3rd column, and I make a raster overlayed on a leaflet map from there.

I feel like I'm probably re-inventing the wheel with this one, and there's probably an easier thing out there. The important point is to generate a grid of coordinates with a spacing and width that I can determine, all centered around a point. Thanks!

This is what the grid looks like, plotted roughly

# Setting a parameter for later
sdist = 20 # search distance radius around each point

# Input location
googleinput = c(39.166178, -105.919274)

mylat = googleinput[1]
mylon = googleinput[2]

# Creating a square
latplus = mylat + 1.8
latminus = mylat - 1.8

lonplus = mylon + 1.8
lonminus = mylon - 1.8

# Doing some geometry to make sure entire area is covered, even w/ 
# repeats
gridspacekm = sdist * sqrt(2)
gridspacecoord = 0.25 # this equals 28 km

# Setting up the x an y axis for this search grid
gridlat = seq(from = latplus, to = latminus, by = -gridspacecoord)
gridlon = seq(from = lonplus, to = lonminus, by = -gridspacecoord)

# Setting up each column for the grid
col1 = rep(gridlat[1], length(gridlon))
col2 = rep(gridlat[2], length(gridlon))
col3 = rep(gridlat[3], length(gridlon))
col4 = rep(gridlat[4], length(gridlon))
col5 = rep(gridlat[5], length(gridlon))
col6 = rep(gridlat[6], length(gridlon))
col7 = rep(gridlat[7], length(gridlon))
col8 = rep(gridlat[8], length(gridlon))
col9 = rep(gridlat[9], length(gridlon))
col10 = rep(gridlat[10], length(gridlon))
col11 = rep(gridlat[11], length(gridlon))
col12 = rep(gridlat[12], length(gridlon))
col13 = rep(gridlat[13], length(gridlon))
col14 = rep(gridlat[14], length(gridlon))
col15 = rep(gridlat[15], length(gridlon))

# finalizing the grid

# All of the x coordinates
x = c(col1, col2, col3, col4, col5, col6, col7, col8, 
      col9, col10, col11, col12, col13, col14, col15)

# All of the y coordinates
y = rep(gridlon, 15)

# Together in a data frame
df = data.frame(x, y)
hminutus
  • 1
  • 1
  • 1
    See `?expand.grid`. I think you've got a dupe of [this R-FAQ on generating all combinations of two vectors](https://stackoverflow.com/q/11388359/903061) – Gregor Thomas Jul 01 '17 at 05:26
  • 1
    You just need `as.data.frame(expand.grid(x = gridlat, y = gridlon))` – Gregor Thomas Jul 01 '17 at 05:27
  • The way to do it a little more manually would be `data.frame(x = rep(gridlat, times = length(gridlon)), y = rep(gridlon, each = length(gridlat)))` – Gregor Thomas Jul 01 '17 at 05:32

0 Answers0