I am trying to reduce duplicated code in a script and in order to do this I am creating some helper functions.
One function I am working on has no arguments that it takes in but rather uses a data set already loaded into the global environment to create a few subsets and then returns those data.frames.
I have created a simple example below that doesn't do exactly what I am describing but will give an idea of how it is structured.
# Create function
my_func <- function(){
a <- as.data.frame("ID" = c(1, 2, 3, 4, 5, 6),
"TYPE" = c(1, 1, 2, 2, 3, 3),
"CLASS" = c(1, 2, 3, 4, 5, 6))
b <- as.data.frame("ID" = c(1, 2, 3, 4, 5, 6),
"STATUS" = c(1, 1, 2, 2, 3, 3))
return(list(a, b))
}
# Call to the function
list[a, b] <- my_func()
The issue I am having is not within the function, but rather when calling the function and trying to store the results. If I call the function like this:
my_func()
It prints the 2 data.frames as a list, however, when trying to assign them names it gives me the error that a does not exist
.
I am assuming I am just returning them incorrectly or trying to store them incorrectly.
Thanks!
UPDATE
For reference the reason I was trying to use this syntax is due to this post: How to assign from a function which returns more than one value?
Also, I was hoping to capture the return in 1 line instead of having to assign it individually.
For example, in this case it is easy enough to assign it as:
test <- my_func()
a <- test[[1]]; b <- test[[2]]
However, if I had a much longer list, this would get very tedious.