R : confusion regarding LHS and RHS of assignment and order of operation -
i having fundamental confusion r. have snippet of r code.
> m <- 1:10 > m [1] 1 2 3 4 5 6 7 8 9 10 > dim(m) <- c(2,5) > m [,1] [,2] [,3] [,4] [,5] [1,] 1 3 5 7 9 [2,] 2 4 6 8 10
now c/python programmer , line dim(m) <- c(2,5)
incredibly confusing me. realize changed vector matrix, looking @ not understand logic/order of operation.
<-
assignment operator in r. me, logically order of operation : assign (2,5) output of dim(m). since output of dim(m) isn't assigned variable, output lost.
could explain how should read line dim(m) <- c(2,5)
? order of operation? seems order of operation using <-
changes depending on lhs and rhs of equation.
these special functions called replacement functions. quote hadley's advanced-r book:
replacement functions act modify arguments in place, , have special name xxx<-. typically have 2 arguments (x , value), although can have more, , must return modified object. example, following function allows modify second element of vector:
`second<-` <- function(x, value) { x[2] <- value x } x <- 1:10 second(x) <- 5l x #> [1] 1 5 3 4 5 6 7 8 9 10
when r evaluates assignment second(x) <- 5, notices left hand side of <- not simple name, looks function named second<- replacement.
you can check full chapter here under replacement functions title.
Comments
Post a Comment