Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to call the `[<-` function in `[` form?

Tags:

function

r

Let's assume that I am a lazy programmer with bad habits (who also happens to not know about plyr/dplyr), I like doing operations like this:

`[<-`((z<-reshape2::melt(iris)), z[,"value"]>5, 3, 100)

Melt iris, then assign the value 100 to the rows where the value is greater than 5, then return all the rows, not just the selected rows. This function is described on the page for ?"["

The same code with replace() (well almost the same)

 z[,"value"] <- replace(i <- ((z <- reshape2::melt(iris))[,"value"]), i > 5, 100)

1) But the question is: is there a way to call the [<- function using the standard bracket notation iris[<-, blah, blah, blah, ?]?

edit July 2016: so the purpose of this question is NOT to replicate the operation. The data doesn't matter, the example doesn't matter, the convoluted way of reshaping the data doesn't matter.

like image 694
Vlo Avatar asked Dec 16 '14 22:12

Vlo


People also ask

How do you call a function in a form tag?

To call and run a JavaScript function from an HTML form submit event, you need to assign the function that you want to run to the onsubmit event attribute. By assigning the test() function to the onsubmit attribute, the test() function will be called every time the form is submitted.

How do you call a function in a JavaScript script?

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.


1 Answers

To answer your question: ofcourse not. For

iris[<-, blah, blah, blah, ?]

to work, the [ function should take another function (or operator) as a second argument, and [ is a primitive that doesn't allow that.

You might argue "but the function is called [<-". It is not. If you write

x[i,j,...]

Then you call a function [ with first argument x, second argument i and so forth. In your line of code, i is the function <-. The assignment operator is a function indeed:

> `<-`
.Primitive("<-")
> `<-`("x",1)
> x
[1] 1

So what you write in that line, boils down to:

`[`(iris, <-, blah, blah ... )

and that will give an error in R's interpreter; the assignment operator is interpreted as an attempt to assign something. This is clearly invalid code.

You might propose using backticks so it becomes:

iris[`<-`, blah, blah, ... ]

which translates to

`[`(iris, `<-`, blah, blah ,... )

but also that is something that is not and never will be allowed by the primitive [.

Some people suggested you could write your own method, and you can - for classes you defined yourself. But you can't redefine [ itself to allow this for any generic data frame, unless you rewrite the R interpreter to recognize your construct as a call to [<- instead of [.

like image 149
Joris Meys Avatar answered Sep 16 '22 18:09

Joris Meys