Using SRTM tif file in R - r

I'm trying to import a SRTM dataset into R. I've downloaded the data in a tif file however am having trouble reading it in "R".
Ive tried using the following code:
t = readTIFF("srtm_56_06/srtm_56_06.tif", as.is=TRUE)
load('srtm_56_06/srtm_56_06.tif')
read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif")
However I am still getting error messages:
load('srtm_56_06/srtm_56_06.tif')
# Error: bad restore file magic number (file may be corrupted) -- no data loaded
# In addition: Warning message:
# file ‘srtm_56_06.tif’ has magic number 'II*'
# Use of save versions prior to 2 is deprecated
library(raster)
t = readTIFF("srtm_56_06/srtm_56_06.tif", as.is=TRUE)
# Error: could not find function "readTIFF"
read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif") + min(read_file)
# Error: unexpected symbol in:
# "read_file<-as.matrix(raster("srtm_56_06/srtm_56_06.tif")
# min"
Can anyone help me with the commands to import this data. I'm a novice at "R" and a little lost.

Just read it with raster, but note you depend on rgdal being installed as well to read a .tif.
library(raster)
library(rgdal)
r <- raster("srtm_56_06/srtm_56_06.tif")
If that works, try
plot(r)
r
If it's really a "TIFF" then that should be fine, if it's really a GeoTIFF then you'll have a sensible map as well. (If it's something else that GDAL can read you might get a good result anyway, remember the extension of a file is not a reliable indicator of its contents).
The SRTM clue suggests that this is a single band DEM file from the tiled global SRTM data set. If it's somehow a "multi-band image" then you could read that with brick and plot with plotRGB (but I really doubt that is the case here). Note that there is a native binary format for SRTM that raster/rgdal could read as well but either they distributed .tif as well or someone else converted it.
There are a number of misconceptions in your code:
load is for a particular file type created from R (not these .tifs)
readTIFF is not in package raster
read_file would be a sensible matrix, if you have rgdal installed (which raster must use to load a .tif), but why throw away the spatial metadata?

Related

unable to open .dat files on R even with haven installed

So I use SGA tools for processing my images. It gives back results in .dat files. Now in order to work on this data in R, I tried to import the .dat file using the haven package. I installed haven and then its library, but I am not able to import data still and it gives this error message.
Error: Failed to parse C:/Users/QuRana/Desktop/SGA Tools/Plate_Image_Example (1).dat: This version of the file format is not supported.
When I use this command install.packages("haven"), haven is loaded, but then when I load library using library(haven) nothing appears on my console except for this
> library(haven)
Then when I use this code:
datatrial1 <- read_dta("C:/Users/QuRana/Desktop/SGA Tools/Plate_Image_Example (1).dat")
It gives me the error mentioned above. When I try converting my .dat file to a .csv file and load my data, the imported data adds additional "t" values before the values in columns except for the first one like this:
Flags: S - Colony spill or edge interference C - Low colony circularity
# row\tcol\tsize\tcircularity\tflags
1\t1\t4355\t0.9053\t
1\t2\t4456\t0.8401\t
1\t3\t3439\t0.8219\t
1\t4\t3215\t0.8707\t
All the t's before the numeric values are not what I want. Another issue that I am facing is I cannot install the gitter package on my R version which is R 4.2.2.
You can read your tab separated file like so `read.delim("file_path", header = TRUE, sep = "\t")

R read and plot gdbtable

I'm very new to gbd table and today at work I was asked to use R to read the data available on https://frap.fire.ca.gov/media/9792/fthrt14_2.zip and plot it using R tools like ggplot and plot_ly.
My problem is that I don't even understand how to read this data with R.
These are the stackoverflow questions I read so far:
- rgdal - read a table within a ESRI geodatabase (gdb)
- How to read a table from an ESRI file geodatabase (.gdb) using R
- How do I get rgdal to open a geodatabase (.gdb) file?
however none of them seems to be working.
These are my steps:
- I unzipped the file in my C:\temp folder. This means I have an R variable file_gdb = "C:/temp/fthrt14_2.gdb"
- then, I have fc_list = ogrListLayers(file_gdb ) and if I print its content I see:
character(0)
attr(,"driver")
[1] "OpenFileGDB"
attr(,"nlayers")
[1] 0
at this point I try fc = readOGR(dsn=fgdb,layer="OpenFileGDB") but I get the following error:
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv
Cannot open layer
and from here I'm quite lost.
Any help would be much appreciated. Many thanks from a complete newbie.

Difficulty opening a package data file of unknown type

I am trying to load the state map from the maps package into an R object. I am hoping it is a SpatialPolygonsDataFrame or something I can turn into one after I have inspected it. However I am failing at the first step – getting it into an R object. I do not know the file type.
I first tried to assign the map() output to an R object directly:
st_m <- maps::map(database = "state")
draws the map, but str(st_m) appears to do nothing, unless it is redrawing the same map.
Then I tried loading it as a dataset: st_m <- data("stateMapEnv", package="maps") but this just returns a string:
> str(stateMapEnv)
chr "R_MAP_DATA_DIR"
I opened the maps directory win-library/3.4/maps/mapdata/ and found what I think is the map file, “state.L”.
I tried reading it with scan and got an error message I do not understand:
scan(file = "D:/Documents/R/win-library/3.4/maps/mapdata/state.L")
Error in scan(file = "D:/Documents/R/win-library/3.4/maps/mapdata/state.L") :
scan() expected 'a real', got '#'
I then opened the file with Notepad++. It appears to be a binary or compressed file.
So I thought it might be an R data file with an unusual extension. But my attempt to load it returned a “bad magic number” error:
st_m <- load("D:/Documents/R/win-library/3.4/maps/mapdata/state.L")
Error in load("D:/Documents/R/win-library/3.4/maps/mapdata/state.L") :
bad restore file magic number (file may be corrupted) -- no data loaded
Observing that these responses have progressed from the unhelpful through the incomprehensible to the occult, I thought it best to seek assistance from the wizards of stackoverflow.
This should be able to export the 'state' or any other maps dataset for you:
library(ggplot2)
state_dataset <- map_data("state")

From POV-Ray to rgl

I've followed this tutorial to export a POV-Ray graphic to a STL file, through Meshlab. I've also tried the export to the OBJ format. Everything seems to work fine from the creation of the POV-Ray graphic to the exporting in Meshlab.
But then I've tried to render the graphic in R with the functions readSTL and readOBJ of the rgl package, and the problem is here.
In fact, the exported STL file is empty:
solid STL generated by MeshLab
endsolid vcg
So, of course, rgl::readSTL renders nothing in R.
The OBJ file is not empty, but it contains no faces (only vertices and vertex normals):
####
#
# OBJ File Generated by Meshlab
#
####
# Object blob.obj
#
# Vertices: 8437
# Faces: 0
#
####
vn -0.900372 -0.267658 -0.343060
v -4.000525 2.600000 -0.833225
......
After running rgl::readOBJ in R the rendering is just a white scene, there's nothing. Even if there's no face, we could expect to get some points.
Maybe I'm mistaken during one step of the procedure. Do you have any idea about:
how to export to a non-empty STL file in Meshlab ?
how to get the points with readOBJ in R ?
how to get the faces in the OBJ file when exporting from Meshlab ?
do you know another way to go from POV-Ray to rgl, if possible preserving the colors ?
Update
I've found a way to get the faces in the OBJ file: instead of doing Screened Poisson Surface Reconstruction in Meshlab, as said in the tuto, I do Surface Reconstruction: Ball Pivoting.
But then rgl::readOBJ generates this error:
Error in order(vlinks[[i]][, 2]) : argument 1 is not a vector
The same procedure allows to export a non-empty STL file. But then rgl::readSTL generates this error:
Error in matrix(NA, 3 * n, 3) : invalid 'nrow' value (too large or NA)
In addition: Warning message:
In matrix(NA, 3 * n, 3) : NAs introduced by coercion to integer range
Ok, I've found.
Follow the linked tuto to create the file blob.asc in POV-Ray
In Meshlab, open this file, and do Surface Reconstruction: Ball Pivoting in the menu Filters -> Remeshing, Simplification and Reconstruction. Perhaps one previously needs to do Screened Poisson Surface Reconstruction before, I don't know.
Export the file as STL. Check "Binary Encoding" (a default option), because rgl::readSTL reads binary STL files only, not ASCII files.
In R, now you can do rgl::readSTL. And this works:

R: Error thrown while using RGDAL and RASTER packages

To whom this may concern:
Here is the source code:
GRA_D1<- raster(files[[1]])
//Sets up an empty output raster:
GRA_D1<- writeStart(GRA_D1,filename='GRA_D1.tif', format='GTiff', overwrite=TRUE)
//Write to the raster, for loop:
for(i in 1:dim(GRA_D1)[1]){
//Extract raster values at rows
d.Frame<- matrix(NA,ncol=2,nrow=dim(GRA_D1)[2])
d.Frame[,1]<- getValues(r1[[1]],i)
d.Frame[,2]<- getValues(r1[[2]],i)
w.Frame<- as.data.frame(d.Frame)
names(w.Frame)<- c("D1_pred_disAg","D1_pred_RK")
//Apply the predictive model:
m.pred<-predict(mod.1, w.Frame)
//Write the predictions to the empty TIFF raster
GRA_D1<-writeValues(GRA_D1,m.pred,i)
print(i)}
//Finish writing to the raster
GRA_D1<- writeStop(GRA_D1)
I am attempting to write output to an empty TIFF raster, but I keep receiving the following error message:
#Error in .local(.Object, ...) :
`general_file_path\GRA_D1.tif' does not exist in the file system,
and is not recognised as a supported dataset name.
I wonder if this is related to misusing functions in either the RGDAL or RASTER package.
Could someone please assist me?
Thanks in advance for your generosity.
Cheers,
AD
Super simple fix. Cannot believe that it is this simple and that it took me this long, but here is the answer:
"rgdal" and/or "GTiff" files don't like the use of underscores in their dataset names.
When running the code with "GRAD1.tif" (instead of "GRA_D1.tif"), all works well.
You really should not be doing any of this, I think, as you could do:
p <- predict(r1, mod.1, filename='GRA_D1.tif')
(and that filename works just fine)

Resources