verystrongjoe - 10 months ago 45

R Question

This line is really difficult for me who is java programmer to understand. I think ' <-' ,the operator , is a assign operator. But how could I understand the internal sub-processes. c(5,4) makes vectors with two values and then how does this value to deliver to the dim function's input? This convention is not good for me to be familiar with this.

`dim(m) <- c(5,4) # Dimensions set to 5 & 4, so m is now a 5x4 matrix`

Answer Source

This is often referred to as "syntactic sugar".

R's objects are theoretically immutable. Doing something like:

```
dim(m) = c(4,5)
```

looks like it is changing `m`

, but in reality the syntax tree is written to be like:

```
m = D(m, c(4,5))
```

where `D`

is a function that constructs a matrix from another matrix and a new set of dimensions. The previous `m`

is now probably up for garbage collection, and the name `m`

now points to the re-dimensioned matrix.

Syntactic sugar like this is used in R in most places where objects seem to mutate, such as `a[1]=2`

, which is expressed in the syntax tree as `a = B(a,1,2)`

, where `B`

is a constructor function that creates a vector from the original `a`

but with the first value set to two.

Note: These assignment functions, `D`

and `B`

in the above examples are actually named `dim<-`

and `[<-`

in R, I called the `D`

and `B`

for clarity because function names with `<-`

look a bit weird but are perfectly acceptable identifiers in R