Fredkho
Fredkho

Reputation: 578

R: Function within a function: managing environments

Within Function A, I have function B that takes 4 objects from the environment of function A and modifies them. Then, I need those objects to be sent back to the environment of function A.

I am looking for best practice recommendation: Currently what I do is: Function B returns a list containing the object and each object is overwritten in the environment of function A. Is there a better way of handling this? The discussions on managing environments are quite complex and this is an important and simple question for the community.

Below is some pseudo code of my implementation

Function A = getObjects(A,B,C){

A= A+1
B= B+1
C= C+1

# Function B returns a list containing the object after certain operations were # performed on these

listFromFunctionB =  FunctionB(A,B,C)

A = listFromFunctionB$A
B = listFromFunctionB$B
C = listFromFunctionB$C

#Other operations keep going on objects A,B and C
}

Upvotes: 2

Views: 68

Answers (2)

Gregor Thomas
Gregor Thomas

Reputation: 145775

It's hard to tell from your toy example, but it seems like you have 3 objects, A, B, and C, that are all operated on together and passed around together. At every step of the way, you take them out of a list, do something to each of them, and put them back in a list so that they can be returned as one from a function.

Generally, this is good. You can't return more than one object, so you need to return them in a list. The waste comes in taking them out of a list each time. Why bother?

In fact, doing the same thing to each item of a list is quite easy with lapply. Your code makes it look like you are copy/pasting lines and changing A to B, then to C. Good programming should involve very little copy/paste.

Rather than writing functions of A, B, C, write functions that expect list(A, B, C) as input.

The only example you have of doing something is adding one to A, B and C. Here is how you would do that if they were in a list:

FunctionA = function(ABClist) {
    # add 1 to each list element
    return(lapply(ABClist, function(x) x + 1))
}

Upvotes: 0

Anton
Anton

Reputation: 1538

Probably there is no better practice than what you have already got.

Functional programming languages (such as R) don't usually allow functions to modify input parameters.

Furthermore, an R function returns only one object, so your returning of the list containing objects A, B, and C is also the correct method.

Upvotes: 2

Related Questions