I have a tiff file which contains 6 bands Data link, I used all methods to extract [See here][2] [see here 2][3] all 6 bands as individual layers but unable to extract them as individual files.
library(raster)
library(ncdf4)
library(rgdal)
r <- raster("E:/TRY/bands.tif")
writeRaster(r, paste0(names(r),".tif"), bylayer=TRUE, format="GTiff")
I get just one tif file and the file doesn't have any information whatsoever like what it is.
Appreciate any help
thanks
Try the function raster::stack. This will read all the layers.
library(raster)
library(ncdf4)
library(rgdal)
s1 <- stack("~/Downloads/bands.tif")
writeRaster(s1, paste0(names(s1),".tif"), bylayer=TRUE, format="GTiff")
Related
I'm trying to select & plot just one of these 9 attributes from my shape file, but nothing seems to work.
Could you help?
enter image description here
It helps if you make a fully reproducible example so that fixers can run the code and be certain that they have resolved the issue.
Here is an example that you will have to modify for your own needs.
library(sf)
fname <- system.file("shape/nc.shp", package="sf") # read a shape file that comes with the sf package
nc <- st_read(fname)
plot(nc) # plot all the data
plot(nc['AREA']) # plot one of the attributes
I'm processing yearly multilayer netCDF files with daily precipitation data from CHIRPS. I have the files for the whole world, each file about 1.2gb large. I need to calculate indices from the precipitation data for each cell in the raster for a specific region. In order to do that I'm trying to crop the files to get a rectangular shape above my area of interest using the raster R package.
This is the code I'm using, exemplary for the first file.
library(ncdf4)
library(raster)
library(rgdal)
# Crop extent
crop_extent <- as(raster::extent(79, 89, 25, 31), "SpatialPolygons")
proj4string(crop_extent) <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
# Set directory with original files
setwd("~/data")
# Read file
chirps81 <- stack("chirps-v2.0.1981.days_p05.nc")
chirps81crop <-crop(chirps1981, crop_extent)
# Write cropped file back to different folder
setwd("~/croppeddata")
writeRaster(chirps81crop, "chirps81crop.nc", overwrite=TRUE)
For some reason however while writing the file the layers lose their name. In the original files and after cropping the names have layer names of the format "X1981.01.01". But after writing and reading the netCDF file with new file <- stack("chirps81crop.nc") the layer names are changed to the format 'X1' up to 'X365'. I think it should be fine working with it, assuming that the order of the layers didn't get mixed up but I don't understand what is happening to the layer names and if this happens because there is something wrong with the code.
It's the writeRaster() function that is losing the layer names, not the crop operation. It is possible to use lower level ncdf functions to assign a numeric value (not a string unfortunately) to each layer which will then show up in the name of the layers after reading. Taking inspiration from the example here, I created some code that shows this.
library(ncdf4)
library(raster)
library(rgdal)
# Crop extent
crop_extent <- as(raster::extent(5.74, 5.75, 50.96, 50.97), "SpatialPolygons")
proj4string(crop_extent) <- "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
# make a sample file
r <- raster(system.file("external/test.grd", package="raster"))
r.latlon <- projectRaster(r, crs = proj4string(crop_extent))
writeRaster(x=r.latlon, filename = 'test.nc', format = 'CDF', overwrite=TRUE)
# read the sample as a 2 layer stack and crop it
test <- stack('test.nc', 'test.nc')
writeRaster(test, 'teststack.nc', overwrite=TRUE, format='CDF')
testcrop <- crop(test, crop_extent)
names(testcrop)
# [1] "test.1" "test.2"
# write the cropped file and make the zname equal to Layer
writeRaster(testcrop, 'testcrop.nc', overwrite=TRUE, format='CDF', zname='Layer')
# open the cdf file directly
nc <- nc_open('testcrop.nc', write = T)
# give the layers numbers starting from 10 so
# we can see them easily
layers = 1:nlayers(testcrop) + 10
layers
# [1] 11 12
ncvar_put(nc, 'Layer', layers)
nc_close(nc)
newtestcrop <- stack('testcrop.nc')
names(newtestcrop)
# [1] "X11" "X12"
nc <- nc_open('testcrop.nc', write = F)
layers = ncvar_get(nc, 'Layer')
layers
# [1] 11 12
nc_close(nc)
So it is possible to get names with numbers under your control when writing the raster, but I don't know enough about your environment to determine if this will help since it might be tricky to map the names you need to a single unambiguous number.
I hope you don't mind me offering a non-R solution, but this task is much easier from the command line using CDO:
cdo sellonlatbox,79,89,25,31 chirps-v2.0.1981.days_p05.nc cropped_file.nc
Which indices did you want to calculate? I suspect it is possible to calculate those quickly and easily with CDO functions too...
I need to get information on the extent, resolution, and cell number of the my file. I'm working with raster files.
You can do
library(raster)
# r <- raster("filename")
r <- raster()
extent(r)
ncell(r)
res(r)
You can read more about the methods in the raster package here
How do I loop through all rasters (TIFF) in a folder and extract values using a point shapefile which has several coordinates then have the output as a dataframe?
library(raster)
library(rgdal)
files <- list.files(path=".", pattern="tif$", full.names=TRUE) # select all the tiff files in the directory
s <- stack(files) # stack all of them using r raster library
shp <- shapefile("points.shp") # read the point shape file
ext <- extract(s, shp) # extract the values from raster stack.
I have read a shapefile using readShapePoly in the maptools package, but cannot read that same file with readOGR. I am hoping someone may be able to help me read the shapefile with readOGR.
I downloaded the file orcounty.shp from here: http://geography.uoregon.edu/geogr/topics/maps.htm
I also downloaded the associated files: orcounty.shx, orcounty.sbx, orcounty.sbn, and orcounty.dbf and put all five files in the folder: c:/users/mark w miller/gis_in_R/shapefile_example/
The following code reads the shapefile and displays some attributes:
library(maptools)
setwd('c:/users/mark w miller/gis_in_R/shapefile_example/')
# Oregon county census data (polygons)
orcounty.poly <- readShapePoly('orcounty.shp', proj4string=CRS("+proj=longlat"))
orcounty.line <- readShapeLines('orcounty.shp', proj4string=CRS("+proj=longlat"))
# see projection
summary(orcounty.poly)
Object of class SpatialPolygonsDataFrame
Coordinates:
min max
x -124.55840 -116.46944
y 41.98779 46.23626
Is projected: FALSE
proj4string : [+proj=longlat]
Data attributes:
However, when I try to read that same shapefile using the following code I receive an error:
library(rgdal)
# read shapefile
oregon.map <- readOGR(dsn="c:/users/mark w miller/gis_in_R/shapefile_example/", layer="orcounty")
# convert to dataframe
oregon.map_df <- fortify(oregon.map)
The error message says:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv) :
Cannot open file
I can read Natural Earth http://www.naturalearthdata.com/ shapefiles using:
library(rgdal)
setwd("c:/users/mark w miller/gis_in_R/")
# read shapefile
wmap <- readOGR(dsn="ne_110m_physical", layer="ne_110m_land")
So, apparently there is a difference between the Natural Earth shapefiles and the Oregon shapefile orcounty.shp.
Thank you for any advice on how to read orcounty.shp with readOGR. My question is similar to the question here: rgdal / readOGR - unable to read shapefile from .zip
Try to remove your last '/' from file path.
readOGR(dsn = 'c:/users/mark w miller/gis_in_R/shapefile_example',
layer = 'orcounty')
For anyone ending up here with this error on a Linux box, I found the problem was using a home path shortcut. i.e.
# Works
readOGR(dsn="/home/user/dir", layer="file")
# Doesn't work
readOGR(dsn="~/dir", layer="file")
I have no idea why.
I used the file ne_110m_land
Try with this:
setwd('D:/JMSR/codes.R/mapas')
unzip("ne_110m_land.zip")
ogrInfo(".", "ne_110m_land")
wmap <- readOGR(".", "ne_110m_land")
raster::shapefile wraps around readOGR to take care of paths and tildes; just pass the full file name.
library(raster)
x <- shapefile("c:/users/orcounty.shp')
or
y <- shapefile("~/users/orcounty.shp")