回收和分配功能(`split< -`)

时间:2013-01-12 14:03:55

标签: r syntax functional-programming

有人可以解释一下这一行R代码的工作原理吗?

split(dat, f) <- lapply(split(dat, f), max)

我认为这只是一个回收规则,但实际上我无法理解。

数据示例:

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

代码执行我想做的事情(按组分配最大值),但问题是这是如何完成的?

2 个答案:

答案 0 :(得分:9)

拆分从矢量中提供值dat[c(1,2,4)]dat[c(3,5,6)]

该作业相当于dat[c(1,2,4)] <- 100 ; dat[c(3,5,6)] <- 300,这就是回收的地方。

<强>被修改

关于发生的情况以及矢量分配结果的原因,请参阅语言定义手册(http://cran.r-project.org/doc/manuals/R-lang.pdf)的第21页。电话:

split(def, f) <- Z

被解释为:

‘*tmp*‘ <- def
def <- "split<-"(‘*tmp*‘, f, value=Z)
rm(‘*tmp*‘)

请注意,split<-.default会返回修改后的矢量。

答案 1 :(得分:5)

感谢评论,答案在split<-.default

只是为了解释它的行为,我在这里用split<-.default调用问题的结果来调用

`split<-.default` <- function(dat, f,value = lapply(split(dat, f), max))
{
    ix <- split(seq_along(dat), f, drop = drop, ...)  ## the call of split here!!
    n <- length(value)
    j <- 0
    for (i in ix) {
        j <- j %% n + 1
        x[i] <- value[[j]]  ## here we assign the result of the first split
    }
    x
}