简体   繁体   中英

Dealing with NA values using extract function in R

I am trying to calculate average annual temperatures for grid cells of 11x11km (except if the cell is coastal, the size is smaller) using the CRU database. The CRS of both vector and raster are the same. However, 332 out of 1363 cells show NA values after the extraction. I want to fill in the NA values before using the dataset for further analysis. Any idea of how I could deal with these missing values? I have looked at several possible solutions on this forum (and others). Unfortunately, none of them don't seem to apply to my case. Below are the details of my workflow:

# load the temperature dataset 
temp <- brick("/CRU/cru_ts4.02.1901.2017.tmp.dat.nc", varname="tmp")
# set CRS for temp
utm = "+proj=utm +zone=49 +datum=WGS84 +towgs84=0,0,0"
tempro = projectRaster(temp, crs = utm, method = "bilinear")
# load the grid cells (in polygons) & set its CRS
fish <- st_read("/CRU/fish11.shp")
fishpro <- st_transform(fish, "+proj=utm +zone=49 +datum=WGS84 +towgs84=0,0,0")
# extract the temperature dataset 
tempgrid  <- extract(tempro, fishpro, fun='mean',  na.rm=TRUE, df=TRUE, weights = TRUE, small = TRUE, 
method='bilinear') 
write.csv(tempgrid, file="temp.csv") 

whereas the map is: temperature

I do not think there is a simple answer to your question. Apparently the polygons are not over land; but we cannot tell as we do not have your data. It could also be that the UTM zone chosen is not appropriate.

I can say that what you are doing is wrong. If you need to transform the data; you should transform the vector data, not the raster data (even if that should not affect the NA problem much, if at all).

library(raster)
temp <- brick("/CRU/cru_ts4.02.1901.2017.tmp.dat.nc", varname="tmp")

fish <- st_read("/CRU/fish11.shp")
fishpro <- st_transform(fish, "+proj=longlat +datum=WGS84")

tempgrid  <- extract(temp, fishpro, fun='mean', na.rm=TRUE, df=TRUE, small = TRUE)
 

You could also make a map to see what is going on (and perhaps include that as an image in your quesiton.

 x <- crop(temp[[1]], extent(fishpro)+1)
 plot(x)
 lines(fishpro)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM