I am working with netCDF-files and have the following problem:
I created 70 objects of "ncdf4" class. They are named ncin1950 - ncin2019. In the next step I need to extract certain information (so called "consecutive_dry_days_index_per_time_period") from the single objects which is regulary done by the following command, using ncin1950 as an example:
cdd.array1950 <- ncvar_get(ncin1950,"consecutive_dry_days_index_per_time_period")
This works perfectly fine.
Since I do not want to apply this command for every single object and thereby 70 times, I tried to use a loop:
for (i in 1950:2019) {
assign(paste0("cdd.array",i), ncvar_get(paste("ncin",i,sep = ""),"consecutive_dry_days_index_per_time_period"))
}
This did not work due to this:
error in ncvar_get(paste("ncin", i, sep = ""), "consecutive_dry_days_index_per_time_period") :
first argument (nc) is not of class ncdf4!
I think the reason for this is the fact that paste() automatically creates results of the class "character":
> class(paste("ncin",1950,sep = ""))
[1] "character"
while
> class(ncin1950)
[1] "ncdf4"
So the question is, how can I keep the "ncdf4" class in the for-loop while using the paste()-function or anything similar which concatenates?
You need get()
to use a string to reference an object, ncvar_get(get(paste("ncin",i,sep = ""))
. Or use mget()
to get the whole list of objects at once, then lapply()
.
Or, best of all, rearrange you upstream workflow so that you're creating a list of objects, rather than cluttering your workspace with 70 different objects. Then you can operate on the list with a for
loop, or lapply
, or fancier methods (e.g. purrr::map()
). This is more idiomatic and will simplify your life in the long run ...