How to Pass the "..." Parameters in the Parent Function to Its Two Children Functions in R

how to pass the ... parameters in the parent function to its two children functions in r

Alternatively you would query a function's formals() to see what named parameters it is expecting and pass along only those. If the "child" function accepts ..., then we will pass along all arguments. This method would not work well for positional arguments.

f_combined <- function(..., .fns =list(f_sqr, f_plus), .reduce=`+`){
dots <- list(...)
Reduce(.reduce, lapply(.fns, function(f) {
if ("..." %in% names(formals(f))) {
do.call(f, dots)
} else if ( any( names(dots) %in% names(formals(f)) ) ) {
do.call(f, dots[names(formals(f))])
} else {
f()
}
}))
}

Here i've set the two functions to run as a parameter (.fns=list(f_sqr, f_plus)) so they can be easily changed or more can be effortlessly added. I've also set a parameter specifying how to combine those values should you want to do something other than sum them (.reduce='+'). But the basic idea is find the best set of mathching named parameters and pass them along. Since your "child" function have default values for their parameters as well, they will run when you pass along no parameters as well.

Here are some example calls

f_combined()
# [1] 3
f_combined(xx=2)
# [1] 6
f_combined(yy=2)
# [1] 4
f_combined(xx = 2, yy = 2)
# [1] 7

In R, How do I properly pass a function and a set of parameters to said function so that it executes properly?

Expanding on my comments:

Here's a simplified version of your functions (so I can make example dataset) -

f <- function (l_candidate, FUN) {
RMSE <- sapply(l_candidate, FUN)
l_min_RMSE <- l_candidate[which.min(RMSE)]
return(l_min_RMSE)
}

g <- function (l, trainset, testset) {
p <- mean(trainset + l)
sqrt(mean((testset - p)^2))
}

trainset <- c(1, 1, 2, 1)
testset <- c(3, 4)

Then:

f(1:5, FUN = function (x) g(x, trainset, testset))
# [1] 2

So you pass the function g via a wrapper function into f and it will do the job for you.

Alternative
R allows you to create a function out of another function:

g <- function (trainset, testset) function (l) {
p <- mean(trainset + l)
sqrt(mean((testset - p)^2))
}

g1 <- g(trainset, testset)
g1(1)
# [1] 1.346291

In this situation, g() takes two arguments, and return a function that takes 1 argument l. So you can create a new function g1() out of g().

Then you can pass it to your parent function giving you the same results in this example:

f(1:5, FUN = g1)
# [1] 2

Passing a function in parent, and params in child

What you want is only possible if you rename the props for MyComponent.

function myGetFunction(config) {

}

function mySaveData(response) {

}

<MyComponent
myGetFunction={myGetFunction}
mySaveData={mySaveData}
/>

Then use prop destructuring in your child.

const MyComponent = ({myGetFunction, mySaveData}) => {

const onRefresh = useCallback(async (getData, saveData) => {

const Response = await myGetFunction(props.config)
props.dispatch( mySaveFunction(Response) )

}, []);

...
}

If myGetFunction is a function that returns the function that you want to use, then you can still do this, but call it like you did.

<MyComponent
myGetFunction={myGetFunction()}
mySaveData={mySaveData()}
/>

The function call in the child is identical.

If you cannot rename the props for some reasons, then you can assign it to a constant and reuse it.

<MyComponent
getData={myGetFunction}
saveData={mySaveFunction}
/>

const MyComponent = ({getData, saveData}) => {
const myGetFunction = getData
const mySaveFunction = saveData

...
}

Passing variables from parent function to child function

The parent function's scope includes child functions, so the child can access them without them being passed. Just leave them out of the parameter list.

function parent(one,two,three,yahoo) {
blabla
blabla
function(what,where,how) {
blabla
//usage of what, where, how, one, two
blabla
}
blabla
blabla
}

For more info, see What is the scope of variables in JavaScript?

How to use trace() for function in parent or child environment?

This question was answered by Duncan Murdoch on R-help Mailing List. I'm posting the answer below:

You are being bitten by normal R scoping. While fun2 is executing, as
soon as it executes the fun1 assignment the name fun1 is bound to the
local function, so when you use fun1 in the first argument to trace(),
you get that one. It will ignore then "where" argument because it was
passed a function object. If you quote the name it will have to do a
lookup and it will use "where". So write fun2 like this:

fun2 <- function() {
fun1 <- function(){
b <- 2
b
}
trace("fun1", browser, where = globalenv())
}

How can I refer to some function from the parent environment (not necessarily defined in the global environment) being in the child environment?

You could have used parent.frame() in place of globalenv() if you want a
function that was visible to the caller of fun2. If you want a function
that was defined with the same environment as fun2, you can usually use
environment(fun2), or parent.env(environment())

Can I refer to some function from the child environment being in the parent environment? I guess not, because of ephemerality?

Sometimes you can, but not usually. If fun2 had returned a value that
referenced the evaluation frame, you would be able to see the "b"
version of fun1 there. But yours didn't. This one would:

fun2 <- function() {
fun1 <- function(){
b <- 2
b
}
trace("fun1", browser, where = globalenv())
environment()
}

Now if you do e <- fun2(), you'll set the trace on the global fun1, but
e$fun1 will be the local one.

Source: https://stat.ethz.ch/pipermail/r-help/2021-December/473434.html

In R - Passing functions and their parameters as parameters to top order function

Use do.call like this and also fix params as shown:

params <- list(list(x = 1, y = 2, z = 3), list(l = 4, m = 5, n = 6))  
pass_thru <- function(FUN, params) Map(do.call, FUN, params)

pass_thru(FUN, params)

giving:

$fun1
[1] 6

$fun2
[1] 120

If you really did want:

params2 <- list(x = 1, y = 2, z = 3, l = 4, m = 5, n = 6)

then try this noting that the params[intersect(...)] part picks out the relevant parameters for the function call:

pass_thru2 <- function(FUN, params) {
runf <- function(f) do.call(f, params[intersect(names(params), names(formals(f)))])
lapply(FUN, runf)
}

pass_thru2(FUN, params2)

giving the same result.

How do you call a parent function from a child component (with parameters) in react-native?

You can't pass a function to onPress with parameters. Instead define an arrow function that executes your clickLocationResult with the parameter like so.

const SearchListItem = props => {
return (
<TouchableOpacity
style={styles.searchListItemContainer}
onPress={() => props.clickLocationResult(props.primaryText)}
>
....
</TouchableOpacity>
);
};

Javascript : Passing variables from parent function to child function

Using this in global scope (outside class) is not a good idea as it pollute the Window object. I will suggest you to create a class and wrap everything like this:

class Dashboard {
constructor(config) {
this.options = config.availableOptions;
this.version = this.options.version;
}

renderDashboard() {
this.createNavbar();
}

createNavbar() {
console.log(this.options, this.version);
}
}

var scriptConfig = {
availableOptions: {
version: "1",
type: "one",
status: "free",
},
availableCategories: {
navbar: true,
hasCoupon: true
}
};

window.addEventListener('load', function () {
const dashboard = new Dashboard(scriptConfig);
dashboard.renderDashboard();
});

Edit ... parameter in R

Arthur and Janhoo made some good suggestions, but in the end I see that the straightforward way I hoped to find doesn't exist. So in the end the best solution to me is the one I sketched in the question:

pars_user= list(...)
pars_default= list(a= 1, b= 2)
pars_fixed= list(c= 3, d= 4)

pars= modifyList(pars_default, pars_user)
pars= modifyList(pars, pars_fixed)
do.call(function, pars)


Related Topics



Leave a reply



Submit