Skip to content

Instantly share code, notes, and snippets.

@amoeba
Created April 8, 2015 17:53
Show Gist options
  • Select an option

  • Save amoeba/929253edf8937d84d15c to your computer and use it in GitHub Desktop.

Select an option

Save amoeba/929253edf8937d84d15c to your computer and use it in GitHub Desktop.
#function that extracts a depth (in meters) from a given lon lat from bathymetric data downloaded from online data using analyzepsat package. The file bathy.rds has already been downloaded by Cindy and is used below for BATH in the function
# General comment: Try to use underscores instead of periods in names, like depth.df => depth_df because
# periods in variable names has special meaning in R and I think it makes code harder to read. This is
# very much personal preference though as it won't make your code not work.
bathy = readRDS(file="bathy.rds")
depth_df <- btrack #this can be any data frame that has lon lat, in this case, column headings are "Lon_E" and "Lat_N"
depth_df$bottom_depth <- NA #setup empty column for bottom depth to be filled by for loop below
# Save the bathy data's lats and lons before we go into the for loop so we aren't generating them again and again
# each iteration of the for loop
bathy_lats <- as.vector(bathy$lat)
bathy_lons <- as.vector(bathy$lon)
# Add two more placeholder columns for the bathy data's lat/lon, which we want to compare to the tag lat/lon later
depth_df$bathy_lat <- NA
depth_df$bathy_lon <- NA
for (i in 1:nrow(depth_df)){
# Retreive the tag lat/lon for this row
tag_lon<-depth_df[i,"Lon_E"]
tag_lat<-depth_df[i,"Lat_N"]
# Find the best indicies to use (nearest lat/lon pair)
# Note: We use the squared difference between the tag lat/lon and the bathy data lat/lons because
# but we could've also used abs() (i.e. which.min(abs(tag_lon - X)))
lon_idx = which.min((tag_lon - X)^2)
lat_idx = which.min((tag_lat - Y)^2)
# Retrieve the values (depth, lat, lon)
depth <- bathy$data[lon_idx, lat_idx]
lon <- bathy_lons[lon_idx]
lat <- bath_lats[lat_idx]
# Update placeholder values with the data we've found
depth_df[i,"bottom_depth"] <- depth
depth_df[i,"bathy_lon"] <- lon
depth_df[i,"bathy_lat"] <- lat
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment