Reputation: 609
My question is fairly difficult to search for, as I just come across APIs for the "equals" function instead!
If I have the following line, working upon the matrix Gl
:
diag(Gl)=diag(Gl)+1
Is this equivalent to modifying Gl
itself?
Upvotes: 1
Views: 74
Reputation: 226192
Yes, this is modifying the diagonal of Gl
in place. This is an example of a moderately obscure R language feature called a replacement function. From the R language manual (section 3.4.4, about the equivalent operation for names
):
The same mechanism can be applied to functions other than
[
. The replacement function has the same name with<-
pasted on. Its last argument, which must be calledvalue
, is the new value to be assigned. For example,
names(x) <- c("a","b")
is equivalent to
`*tmp*` <- x
x <- "names<-"(`*tmp*`, value=c("a","b"))
rm(`*tmp*`)
(sorry about formatting). You can print the `diag<-`
function to see (surround the name in back-ticks ` `
) so the parser doesn't get confused, or getAnywhere("diag<-")
)
Upvotes: 2
Reputation: 1959
Yes, it's assigning. Simple example:
> g1 <- matrix(1:4, nrow = 2, ncol = 2)
> g1
[,1] [,2]
[1,] 1 3
[2,] 2 4
> diag(g1) = diag(g1) + 1
> g1
[,1] [,2]
[1,] 2 3
[2,] 2 5
When you type "dia", then RStudio autofills with the options of diag()
and diag<-
, with some info on the replacement part.
Upvotes: 2