I have a problem with spatial data. I need to extract temperature data from a NetCDF file; then I need to associate this temperature at given latitude and longitude to another set of latitude and longitude contained in a different dataframe. This is the code I used to extract my variables:
myfile <- nc_open(paste(wd, 'myfile.nc', sep=''))
timearr = ncvar_get(myfile, "time")
temp <- ncvar_get(myfile, 'temp_srf')
lat <- ncvar_get(myfile, 'lat_rho')
lon <- ncvar_get(myfile, 'lon_rho')
dim(temp)
[1] 27 75 52 # which means: 27 longitude * 75 latitudes * 52 time steps
I chose to work on the first time step of temperature for now. So:
> t1 <- as.vector(temp[,,1])
Then I created a data.frame including lat, lon and temperature in the first time step:
lat1 <- as.vector(lat)
lon1 <- as.vector(lon)
df1 <- as.data.frame(cbind(lon1, lat1, t1))
head(df1)
lon1 lat1 t1
1 18.15338 40.48656 13.96225
2 18.24083 40.55126 14.36726
3 18.32845 40.61589 14.53822
4 18.41627 40.68045 14.78643
5 18.50427 40.74495 14.88624
6 18.59246 40.80938 14.95925
In another data frame (df2) I have some random points of latitude and longitude, that I have to associate to the closest latitude and longitude of the previous data.frame:
> df2 <- read.csv(paste(id, "myfile.csv", sep=""), header=TRUE, sep=",")
> head(df2)
LONs LATs
1 14.13189 43.41072
2 14.13342 43.34871
3 14.09980 43.40822
4 14.05338 43.72771
5 13.91311 43.88051
6 13.98500 43.91164
I was thinking to get the distance between each point and get the lowest one, but I don't know how to do it. Not sure if there are other solutions.