The problem here seems to be (and hard to be certain without more code or examples) that you have spatial data objects saved in multiple .RDA files and need to read them in a loop.
The struggle is because load
loads things into, by default, the global environment under whatever name they were saved as, and load
returns the name. Thinking that load
returns the object itself and passing that to spatial functions will result in the functions being fed character strings instead of objects.
There's a couple of fixes, the neatest, I think, is to load the files into a new environment. Let's save x
and remove it:
> x = 1:10 ; save(x,file="x.rda") ; rm(x)
> x
Error: object 'x' not found
If we load it back we magically get x
back. The load
itself returns invisibly:
> load("x.rda")
> x
[1] 1 2 3 4 5 6 7 8 9 10
If we clean up and try again, but save the return from load
, you'll see it is the name of the object loaded:
> rm(x)
> z = load("x.rda")
> z
[1] "x"
> x
[1] 1 2 3 4 5 6 7 8 9 10
load
can read to a different environment, so let's write a function that returns the object in a new environment:
> getRDA = function(f){e = new.env();load(f, env=e); return(e)}
so, starting without an x
:
> rm(x)
Warning message:
In rm(x) : object 'x' not found
Use the function to read from x.rda
- x
is not created:
> e = getRDA("x.rda")
> x
Error: object 'x' not found
But you can get it from the returned e
:
> e$x
[1] 1 2 3 4 5 6 7 8 9 10
You can get the name of the thing loaded:
> names(e)
[1] "x"
which might be useful if you have coded information into the name, like "rainfall_1990_12"
.
If you don't care about the name or if it is encoded into the RDA filename then you can modify getRDA
to return the object directly:
> getRDA = function(f){e = new.env();load(f, env=e); return(e[[names(e)]])}
> getRDA("x.rda")
[1] 1 2 3 4 5 6 7 8 9 10
regionX-yearY
is evaluating to a character value. Why? Load one in and print it out to check. Its not aSpatialPolygonsDataFrame
. Of course looping over files withlist.files
creates characters, that's whatlist.files
does.list.files()
returns characters -- but evidently I misunderstood how to loop through the resulting list toload()
the files to manipulate them. I see a lot of examples of binding text/csv files to dataframes, though.