Reputation: 17
I have certain files (VI3g raster data) that I want to read in. The names of the files that I want to read in, are saved in a vector called 'filename' (where the first element of the vector is the name of the first file that I want to read in), and the variable names(where the first element of the vector is the name of the first variable that I want to read in) that I want to assign them to is called 'varname'.
filename varname
file1.VI3g variable_xy
file2.VI3G variable_z
... ...
My approach (that works) to this was the following:
for (i in 1:12) {
assign(varname[i], ReadVI3g(filename[i]))
}
But the data are Rasterlayer. What I would need for my further calculations, are vectors, as some calculations do not work with Rasterlayers. So my approach was to transform the data via getValues in order to get vectors instead of Rasterlayer.
for (i in 1:12) {
assign(varname[i], ReadVI3g(filename[i]))
varname[i]<- getValues(varname[i])
}
This however does not work. I get the message:
Error in (function (classes, fdef, mtable) : unable to find an
inherited method for function ‘getValues’ for signature ‘"character",
"missing", "missing"’
I understand the problem, but I am not able to find a solution. I tried to get around the problem with assign as well, but it did not work either.
And follow up question: As I am new to R, I have the tendency to solve quite a lot of things with loops. I know that it is inefficient and that there are often smarter solutions. Is there an easy way to avoid the loop here?
Thank you very much in advance.
Upvotes: 0
Views: 213
Reputation: 15784
I would go with the following idea:
apply(df,1,function(x) { assign(x['varname'], getValues(ReadVI3g(x['filename'])), env=.GlobalEnv) })
The env=.GlobalEnv
is needed so the variable_xy
is set up in the GlobalEnv and not only in the inner function scope.
side note: loops are not inherently inefficient, but they have to be used wisely, prefer the *apply family when possible.
Upvotes: 0