Reputation: 3188
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.
Upvotes: 15
Views: 886
Reputation: 108523
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 [
.
Upvotes: 3