Reputation: 11
I am trying to read temperature data in R using a NOAA OI SST .nc file. I have temperature data per month, but, I am having trouble extracting the monthly average temperature data from the coordinates I want and putting it into a dataframe.
I'm new at this, any help or pointers are most appreciated.
setwd("~/temperatura/noaa"
prueba<-nc_open("sst.mnmean.nc")
#EXTRAER DATOS
lon<-ncvar_get(prueba,"lon")
lat<-ncvar_get(prueba,"lat")
time<-ncvar_get(prueba,"time")
time=as.Date(time, origin="1800-1-1",tz="UTC")
sst=ncvar_get(prueba,"sst")
unit<-ncatt_get(prueba,"sst","units")$value
I tried to make a matrix but in time I only have numbers and not the months
matriz <- data.frame(cbind(time,lon,lat,sst))
names(matriz) <- c("time","lon","lat","temperature")
time lon lat temperature
1 4352 0.5 89.5 -1.79
2 4383 1.5 88.5 -1.79
3 4414 2.5 87.5 -1.79
4 4442 3.5 86.5 -1.79
5 4473 4.5 85.5 -1.79
6 4503 5.5 84.5 -1.79
7 4534 6.5 83.5 -1.79
8 4564 7.5 82.5 -1.79
9 4595 8.5 81.5 -1.79
like this
Upvotes: 0
Views: 770
Reputation: 3397
The simplest way to read a .nc file to a dataframe in R is tidync. This is done easily. You will probably have to handle times manually, based on your calendar. I don't think tidync currently has the ability to decode them. If I am correct, the files you are using have a calendar such that the dates are saved as the number of days since 1978-01-01. So you will need to calculate the dates in each file based on this. The following should work:
tidync::tidync("sst.mnmean.nc") %>%
tidync::hyper_tibble() %>%
mutate(date = lubridate::ymd("1978/01/01") + lubridate::days(time))
Upvotes: 1
Reputation: 8146
You can use raster
package for that like
library(raster)
r <- brick("sst.mnmean.nc")
r
plot(r, 1)
#Provide longitude & latitude
x1 <- c(0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5)
y1 <- c(89.5, 88.5, 87.5, 86.5, 85.5, 84.5, 83.5, 82.5, 81.5)
points <- cbind(y1,x1)
#Make points as saptial points
spts <- SpatialPoints(points, proj4string=CRS("+proj=longlat +datum=WGS84"))
#Plot those points
plot(spts, add = TRUE)
#Extract raster values
ex1 <- extract(r, spts, fun='mean', na.rm=TRUE, df=TRUE, weights = TRUE)
#To get the date of the raster you can use
idx <- getZ(r)
#Write the extracted vaues in .csv file for further processing
write.csv(t(ex1[-1]), "File_name.csv", row.names = idx)
Upvotes: 1