All,
I have a relatively simple question - when I have multiple data sets and I wish to apply multiple functions on these data sets within a loop, how can I reference these data sets using a variable. For example:
# Generate some test data
Test1 <- runif(10,min = 0,max = 150)
Test2 <- runif(10,min = 0,max = 150)
Test3 <- runif(10,min = 0,max = 150)
# Access the data sets using a variable within loop
for (i in seq(1, 3, 1))
{
print(i)
print(eval(parse(paste0("Test",i))))
}
The above piece of code yields the following error :
**Error in file(filename, "r") : cannot open the connection
In addition: Warning message:
In file(filename, "r") :
cannot open file 'Test1': No such file or directory
**
not sure exactly if it will answer your question but to access the data of Test1 in the first iteration of the for loop and then Test2... you can use that
...but eval(parse(...)) is a discouraged idiom unless you're operating on the language, which is a decidedly advanced topic. for loops are rarely necessary in R, either; you can either use vectorized operations or iterate with lapply and friends.
A more elegant way to collect the results would be with get (which looks for a single variable with a name matching the passed string) or mget (which looks for a vector of names and returns a list):