I am currently trying to extract rainfall data from Mexico from the CHIRPS database. The goal is to get a comprehensive database of monthly rainfall over a period of 15 years. This involves merging a lot of columns after extracting the data from .tif-files which contain the information on weather conditions in a specific months.
CVE_ENT and CVE_MUN are the two variables that later on help me to identify individual municipalities.
Running my code in R and looking at the resulting data frame everything looks fine. However, as soon as I try to extract it to become a .dta or .csv file, I get the following error message: fwrite(vextractall, file="rainfall55.csv") Error in fwrite(vextractall, file = "rainfall55.csv") : Column 4's length (1) is not the same as column 1's length (2456)
The error occurs for multiple other scenarios e.g. if using write.dta.
Anyone who possibly knows on what I am missing out on? Thanks a lot in advance.
#Data get methods#
tif.raster1 <- raster('chirps-v2.0.1999.01.tif')
crs.LL <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84"
tif.raster1 <- projectRaster(tif.raster1, crs = crs.LL)
mexico2shp <- readOGR(dsn='GIS Mexican Municipalities', layer='Mexican Municipalities')
tif.raster1 <- crop(tif.raster1, extent(mexico2shp))
vras.tif1 <- velox(tif.raster1)
iters <- nrow(mexico2shp)
#mapping function#
vextractall <- vras.tif1$extract(mexico2shp, fun=mean)
mexicomm <- as.data.frame(mexico2shp)
vextractall <- as.data.frame(vextractall)
iters <- nrow(mexico2shp)
x <- foreach(a=1:iters) %do% {
if(is.na(vextractall[a,1])) {
ext <- raster::extract(tif.raster1, mexico2shp[a,], fun=mean)
vextractall[a,1] <- ext[1,1]
}
}
vextractall<-as.data.frame(vextractall)
vextractall$CVE_ENT <- mexicomm[,c("CVE_ENT")]
vextractall$CVE_MUN <- mexicomm[,c("CVE_MUN")]
vextractall<-vextractall[,c(ncol(vextractall), 1:(ncol(vextractall)-1))]
vextractall<-vextractall[,c(ncol(vextractall), 1:(ncol(vextractall)-1))]
vextractall <- plyr::rename(vextractall, c("V1"="Milimeters011999"))
tif.raster1 <- raster('chirps-v2.0.1999.02.tif')
tif.raster1 <- crop(tif.raster1, extent(mexico2shp))
vras.tif1 <- velox(tif.raster1)
crs.LL <- "+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84"
tif.raster1 <- projectRaster(tif.raster1, crs = crs.LL)
vextract2 <- vras.tif1$extract(mexico2shp, fun=mean)
vextract2 <- as.data.frame(vextract2)
iters <- nrow(mexico2shp)
foreach(a=1:iters) %do% {
if(is.na(vextract2[a,1])) {
ext <- raster::extract(tif.raster1, mexico2shp[a,], fun=mean)
vextract2[a,1] <- ext[1,1]
}
}
vextractall<-as.data.frame(vextractall)
vextract2<-as.data.frame(vextract2)
vextractall$Milimeters021999 <- vextract2