Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment using call()

Tags:

Suppose I want to manipulate function body like this:

> f1 = function(a, b, d) {
+   stop("This is a template!")
+   result
+ }
> body(f1)[[2]] = call("<-", as.name("result"), lapply(letters[1:2], as.name))

This looks good...

> f1
function (a, b, d) 
{
    result <- list(a, b)
    result
}

...but doesn't work:

> f1(a = 123, b = 456, d = 999)
[[1]]
a

[[2]]
b

On the other hand, when I do this:

> body(f1)[[2]] = call("<-", as.name("result"),
+                      as.call(c(as.name("list"), lapply(letters[1:2], as.name))))

It looks the same...

> f1
function (a, b, d) 
{
    result <- list(a, b)
    result
}

...but it works:

> f1(a = 123, b = 456, d = 999)
[[1]]
[1] 123

[[2]]
[1] 456

Can somebody please break this down for me into some really small pieces and explain what exactly is happening here?

like image 768
jakub Avatar asked Jan 20 '20 22:01

jakub


People also ask

What is Call () in JavaScript?

The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.

Can assign to function call?

The “SyntaxError: can't assign to function call” error is raised when you try to assign a function call to a variable. This happens if you assign the value of a function call to a variable in reverse order. To solve this error, make sure you use the correct syntax to declare a variable.

How do you fix expected assignment or function call?

The React. js error "Expected an assignment or function call and instead saw an expression" occurs when we forget to return a value from a function. To solve the error, make sure to explicitly use a return statement or implicitly return using an arrow function.

What is a function call?

A function call is an expression that passes control and arguments (if any) to a function and has the form: expression (expression-listopt) where expression is a function name or evaluates to a function address and expression-list is a list of expressions (separated by commas).


1 Answers

The problem is that deparse is not perfect. Incidentally this is unrelated to the assignment; the same problem exists when the expression is used in a different context, e.g.:

bquote(1 + .(lapply(letters[1:2], as.name)))

or

bquote(sum(.(lapply(letters[1:2], as.name))))

Either way, you’re constructing a list of names, but you are not constructing a call to list inside an unevaluated expression. But (I’m guessing that) the R deparser doesn’t know what to do with a list of names in an expression, since that situation can’t occur in real R code that isn’t constructed via unevalued expressions.

like image 128
Konrad Rudolph Avatar answered Sep 20 '22 17:09

Konrad Rudolph