'Suddenly error 'Cannot create a RasterLayer object from this file.' in script that worked before

I have a script where I read a raster stored as .tif :

f_treecover   <- raster('Landcover_data/treecover_res_100_q.tif')       

The script used to run fine a few months ago, but now I get the following error message:

Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  : 
  Cannot create a RasterLayer object from this file.

I can read the file with the 'rast' function in terra:

f_treecover   <- rast('Landcover_data/treecover_res_100_q.tif')      
> f_treecover
class       : SpatRaster 
dimensions  : 1400, 3600, 1  (nrow, ncol, nlyr)
resolution  : 0.1, 0.1  (x, y)
extent      : -180, 180, -60, 80  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
source      : treecover_res_100_q.tif 
name        : treecover_res_100_q 

However, all the other objects in the script are RasterLayers , so I need this object to be one as well. I tried coercing the resulting SpatRaster into a Raster with

raster(f_treecover)

, but that leads to the same error message as when originally trying to read the .tif file.

I probably installed an updated version of the raster package in the meanwhile (now using 3.4-10), could that be causing the issue?



Solution 1:[1]

Finally, the problem was solved by completely removing and re-installing R. I had tried that earlier but apparently the un-installation was incomplete, as evidenced by the fact that packages I had installed previously were available again upon re-installation of R.

Solution 2:[2]

If you do not have the rgdal package installed, you get

Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer",  : 
  Cannot create RasterLayer object from this file; perhaps you need to install rgdal first

In which case you should install rgdal

Otherwise, make sure you are not loading an old workspace (use unlink(".RData"), quit R without saving the workspace and start again.

If that does not help: uninstall R and install the latest version and packages again.

Solution 3:[3]

Can also be if a tif name has a character not recognised, e.g. ? in M?ui.

Solution 4:[4]

This happened to me after having no issues prior. I realized what happened was my Dropbox account was not synced and so the file was simply not being found. If you store your raster .tif object in your environment and run the code chunk below it should find your file. If not, Dropbox sync (if your file is from Dropbox) may also be your issue:

readr::read_file(tif_file)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lena
Solution 2
Solution 3 TJeff
Solution 4 Alexi Kim