Wednesday, March 30, 2016

Useful R tips #4

Unpacking lists into objects


















Suppose we have a function which returns a list containing several 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 alphabw,  evalsstpflag 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