"error in nc_open trying to open file" when calling raster() - r

#Crop Vietnam
lst <- raster(destPath, varname = 'tbb_14')
lst_crop <- crop(lst, ext_VN)
lst_crop <- lst_crop - 273.15
#Write output raster
outFilename <- paste(substr(j,1, nchar(j)-15),'_tbb_14.tif', sep='')
writeRaster(lst_crop, paste(extractedFolder + '/tbb_14/', outFilename, sep=""))
How should I fix the problem? I've tried to change path, grant permission for user, diving on the Internet to find a way, but there was nothing solved

You do this
lst <- raster(destPath, varname = 'tbb_14')
That fails, suggesting that destPath does not exist. You can see for yourself with
file.exists(destPath)
Once you have the correct filename, you can also replace "raster" with "terra", like this
library(terra)
x <- rast(destPath, 'tbb_14')

Related

Using R to loop through downloading of files and renaming it

I would like to download multiple files from a list of urls. Some of the urls may be invalid and I would like to skip it if there is error.
If possible, would also like to rename the downloaded file based on the ID.
Appreciate if someone could help me out. A sample of my data is as follow:
ID <- c('L18491','K18781','I28004')
url <- c('https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_50.xlsx',
'https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_101.xlsx',
'https://file-examples-com.github.io/uploads/2017/02/file_example_XLSX_100.xlsx')
df <- data.frame(ID, url)
We can use possibly from purrr
library(purrr)
out_lst <- map(df$url, pfun)
names(out_lst) <- df$ID
where
pfun <- possibly(f1, otherwise = NA)
where
f1 <- function(urllink) {
openxlsx::read.xlsx(urllink)
}
Or another option is tryCatch
f2 <- function(urllink) {
tryCatch(openxlsx::read.xlsx(urllink),
error = function(e) message("error occured"))
}
out_lst2 <- lapply(df$url, f2)
If we want to use download.file
lapply(seq_along(df$url), function(i)
tryCatch(download.file(df$url[i], paste0(getwd(), "/", df$ID[i], ".xlsx")),
error = function(e) message("error occured")))
Or using iwalk
library(tibble)
pfun2 <- possibly(download.file, otherwise = NA)
iwalk(deframe(df), ~ pfun2(.x, as.character(glue::glue('{getwd()}/{.y}.xlsx'))))
You can use download.file to download the file and name it according to ID variable.
Map(function(x, y) tryCatch(download.file(x, sprintf('%s.xlsx', y)),
error = function(e) {},
warning = function(w) {}), df$url, df$ID)
This will download the files in your working directory and name it as ID.xlsx. Also it will skip any error or warnings generated.

Saving images with Magick

I'm trying to automate adding my signature to my photos using the magick package - but I'm having problems saving them.
Here's my code:
file_list <- dir(".", pattern = "*.png")
mySig <- image_read("~/Desktop/sig1.png")
mySig <- mySig %>% image_resize("300x300")
newPhotos <-
for (i in 1:length(file_list)) {
img <- image_read(file_list)
photoSig <- img %>%
image_composite(mySig, gravity = "southeast", offset = "+20+20")
newName <- as.character(paste0("New_", file_list))
image_write(photoSig, newName, format = "png")
}
And I get the following error regardless of the script being in or out of a loop:
Error in file(con, "wb") : invalid 'description' argument
On top of this - even when I don't automate the name and just have the output called "test" or something - it only saves one of the photos and not all of them. What am I doing wrong? Thanks!

CHIRPS data for variable in a loop using R

This program must download the CHIRPS data according to the detail entered, and then assign each year of information in a variable 'nc' and export it as '.csv'. However, the code does not work and I received the message "R Session Failed Failed Error" in RStudio.
### Importing libraries
library(parallel)
library(sp)
library(raster)
library(heavyRain)
### Working directory
setwd("D:/data-science_hydrology/g8/")
### Download CHIRPS monthly
data_CHIRPS <- getCHIRPS(region = "global",
format = "netcdf",
tres = "daily",
sres = 0.25,
begin = as.Date("1981-01-01"),
end = as.Date("2020-12-31"),
dsn = "data/chirps_daily",
overwrite = T,
cores = 1)
### THIS CRASH ME RSTUDIO
for (i in 1981:1982){
nc <- paste("nc", i, sep = "")
assign(nc, brick(paste("data/chirps_daily/chirps-v2.0.", i, ".days_p25.nc", sep ="")))
}
First, you should never use assign; rather store the objects you create in a list. You can nornally do that like this
library(raster)
y <- 1981:1982
ff <- paste0("data/chirps_daily/chirps-v2.0.", y, ".days_p25.nc")
nc <- lapply(ff, brick)
names(nc) <- y
That will probably give the same error, most likely because of a corrupted file. To find out which, use a loop to see where it fails.
nc <- list()
for (i in 1:length(ff)) {
print(ff[i]); flush.console()
nc[[i]] <- brick(ff[i])
}
And then re-download the bad file and try again.

Error writing raster in for loop

-
I am beginner in R and I have made a script where I convert a .grd file into .tif file in a for loop (I have quite a lot of .grd files that should be converted). The script is as you can see below.
# Set your work directory
setwd("xxx")
library(rgdal)
library(sp)
library(raster)
# Data: .grd files in order to reproduce the code below
g1 <- raster(ncol=10, nrow=10)
vals <- 1:100
g1 <- setValues(g1, vals)
writeRaster(g1, filename="TEST_G1.grd", overwrite=TRUE)
g2 <- raster(ncol=50, nrow=50)
vals <- 1
g2 <- setValues(g2, vals)
writeRaster(g2, filename="TEST_G2.grd", overwrite=TRUE)
# Convert .grd to geotif in a for loop
rlist <- list.files(pattern=".grd$")
for (i in rlist)
{
#Read raster
x <- raster(rlist[i])
#make new file name
filename <- rlist[i]
n <- unlist(strsplit(filename, split='.', fixed=TRUE))[1]
name <- paste(n, ".tif", sep="")
#write the raster as GTiff
writeRaster(x, filename=name, format="GTiff", overwrite=TRUE)
}
I have run all sentences in the script separately and managed to get geotif file. However, when I run the lobe I get the following error:
Error in .local(.Object, ...) :
Error in .rasterObjectFromFile(x, band = band, objecttype = "RasterLayer", :
Cannot create a RasterLayer object from this file. (file does not exist)
The file does exist, and when I just run the last line separately the tif file is created... so I don't understand what is wrong with the loop.
If I e.g. write "for (i in 1:2)" instead of "for (i in rlist)" it works. but I would prefer not to count the number of files in every directory, which is the reason I was trying to use "for (i in rlist)"
Thanks a lot for you help!

R function displays object "obser" but won't write.CSV

My code works and displays the correct values on screen for print(obser) but will not write the .csv and when I tried str(obser) it gave error object 'obser' not found. I have tried various online help and books and the function is correctly written.
If instead of running the function in the console in RStudio, I run line by line in the scrip screen will the csv then be created?
complete <- function(directory= "specdata", id = 1:332){
# directory <- "specdata"
# id <- 1:332
files_list <- list.files(path=directory,full.names=T)[id]
NumOfFiles <- length(files_list)
obser <- data.frame()
indivFile <-data.frame()
nobserv <- vector(mode= "integer", length = NumOfFiles)
for (i in 1:NumOfFiles){
indivFile <- read.csv(files_list[i]) # read data file into df inc NA's
indivFile <- na.omit(indivFile) # removes NA prev file
x <- nrow(indivFile[1])
nobserv[i] <- x
}
x_name <-"ID"
y_name <-"nobs"
obser <- data.frame(id, nobserv)
return(obser) # object returned
print(obser)
wd <- getwd()
setwd(wd)
write.csv(obser, file="Observations2.csv")
}
Try and save the object returned from the function. Ergo:
output<-complete("specdata",id=1:332)
write.csv(output,"Observations2.csv",row.names=F)

Resources