Unpacking lists into objects
X = list('alpha' = alpha, 'b' = b, 'w' = w, 'evals' = evals, 'stp' = stp, 'flag' = flag)
return(X)
We can unpack this list into the individual objects using
for (i in 1:length(X)) { assign(names(X)[i], X[[i]]) }
ls() will show objects alpha, b, w, evals, stp, flag now defined in the current environment/scope.
Now, suppose we wanted to mimic Matlab/GNU Octave's way of being able to return multiple objects without having to rewrite those lines of code above? We can implement an unpack() function that will unpack the list inside the caller's environment/scope:
unpack <- function(X) {
# assign to objects in the parent/calling frame
for (i in 1:length(X)) {
assign(names(X)[i], X[[i]], envir = parent.frame())
}
}
To use:
result = examineExampleP(i, glob, alpha, w, b, X, Y, krnel, kpar1, kpar2, C, tol, steps, stp, evals, eps, K)
unpack(result)
or simply
unpack( examineExampleP(i, glob, alpha, w, b, X, Y, krnel, kpar1, kpar2, C, tol, steps, stp, evals, eps, K) )
Both will unpack the list returned by the function into the objects in the caller's environment/scope. When called from the console, it will be unpacked into the global environment.
No comments:
Post a Comment