[R] increase or decrease variable by 1
Duncan Murdoch
murdoch.duncan at gmail.com
Tue Dec 7 20:47:19 CET 2010
On 07/12/2010 12:42 PM, Gabor Grothendieck wrote:
> On Tue, Dec 7, 2010 at 12:25 PM, Bert Gunter<gunter.berton at gene.com> wrote:
>> Ted:
>>
>> Inline below...
>>
>> On Tue, Dec 7, 2010 at 8:42 AM, Ted Harding<ted.harding at wlandres.net> wrote:
>>> Indeed!
>>>
>>> x<- x + 1
>>>
>>> (and being generous with unnecessary spaces) uses 10 characters.
>>>
>>> `+`(x)<-1
>>>
>>> (being mean with them) uses 9. The "mean" version of the first
>>> uses only 6: x<-x+1
>>>
>>> However, I suppose there is merit in the spiritual exercise
>>> of contemplating how `+`(x)<-1 gets worked out!
>>
>> AFAICS it doesn't.
>>> `+`(x)<-1
>> Error in +x<- 1 : could not find function "+<-"
>
> Sorry, my code was missing the first line:
>
>> `+<-`<- `+`
>>
>> x<- 3
>> `+`(x)<- 1
>> x
> [1] 4
Note that there are at least two subtle differences between your code
and x += 1 or ++x:
First, the value of `+`(x)<- 1 is 1, i.e.
print(`+`(x)<- 1)
will give 1 regardless of x, unlike ++x.
Another difference is that `+`(x)<- 1 is equivalent to x <- x + 1, and
in R, that doesn't necessarily increment x: the x on the right hand
side might be a global variable, and the result of x + 1 will be
assigned to a new local variable. For example, the sequence
x <- 3
f <- function() `+`(x)<- 1
f()
x
leaves x set to 3. (But it temporarily created a new variable called x
in the evaluation frame of f().)
I don't think the first difference is documented; I haven't checked the
source to know if it's intentional. (It generally makes sense that "foo
<- bar" has value bar; the problem is that your "assignment" doesn't
follow the rule that it assigns bar to foo.)
The second one is a basic fact of life in R, and the source of a few
bugs: the only way around it that I can see would be to allow users to
declare things about variables (e.g. "x is a global variable, don't
create a local when I assign to it!").
Duncan Murdoch
More information about the R-help
mailing list