Can someone please explain me how this one line of R code works?
split(dat, f) <- lapply(split(dat, f), max)
I thought it is a just a recycling rule but really I can’t understand it.
Data example :
dat <- c(1, 2, 3, 100, 200, 300)
f <- as.factor(c("a", "a", "b", "a", "b", "b"))
split(dat, f) <- lapply(split(dat, f), max)
dat
[1] 100 100 300 100 300 300
The code do what I want to do (assign the max by group) but the question is how this is done?
The split gives the values
dat[c(1,2,4)]anddat[c(3,5,6)]from the vector.The assignment is equivalent to
dat[c(1,2,4)] <- 100 ; dat[c(3,5,6)] <- 300and this is where the recycling takes place.Edited
As for what happens, and why a vector assignment results, see page 21 of the language definition manual (http://cran.r-project.org/doc/manuals/R-lang.pdf). The call:
Is interpreted as:
Note that
split<-.defaultreturns the modified vector.