How do references work in R?

Posted by djechlin on Programmers See other posts from Programmers or by djechlin
Published on 2014-06-08T22:54:22Z Indexed on 2014/06/09 3:41 UTC
Read the original article Hit count: 278

Filed under:
|

I'm finding R confusing because it has such a different notion of reference than I am used to in languages like C, Java, Javascript... Ruby, Python, C++, well, pretty much any language I have ever programmed in ever.

So one thing I've noticed is variable names are not irrelevant when passing them to something else. The reference can be part of the data. e.g. per this tutorial

a <- factor(c("A","A","B","A","B","B","C","A","C"))
results <- table(a)

Leads to $a showing up as an attribute as $dimnames$a.

We've also witnessed that calling a function like a <- foo(alpha=1, beta=2) can create attributes in a of names alpha and beta, or it can assign or otherwise compute on 1 and 2 to properties already existing. (Not that there's a computer science distinction here - it just doesn't really happen in something like Javascript, unless you want to emulate it by passing in the object and use key=value there.)

Functions like names(...) return lvalues that will affect the input of them.

And the one that most got me is this.

x <- c(3, 5, 1, 10, 12, 6)
y = x[x <= 5]
x[y] <- 0

is different from

x <- c(3, 5, 1, 10, 12, 6)
x[x <= 5] <- 0

Color me confused. Is there a consistent theory for what's going on here?

© Programmers or respective owner

Related posts about programming-languages

Related posts about r