【问题标题】:Recycling and assignment functions (`split<-`)回收和分配功能(`split<-`)
【发布时间】:2012-12-26 23:21:13
【问题描述】:

谁能解释一下这行 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

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

【问题讨论】:

  • `split&lt;-.default`
  • R 手册中另一个可爱的 kaboom 时刻

标签: r syntax functional-programming


【解决方案1】:

拆分给出向量中的值dat[c(1,2,4)]dat[c(3,5,6)]

分配等同于dat[c(1,2,4)] &lt;- 100 ; dat[c(3,5,6)] &lt;- 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&lt;-.default 返回修改后的向量。

【讨论】:

  • 谢谢!我喜欢这个答案。你需要解释为什么我们得到一个向量而不是一个列表作为结果。
【解决方案2】:

感谢评论,答案在split&lt;-.default

只是为了解释它的行为,我在这里调用split&lt;-.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
}

【讨论】:

    猜你喜欢
    • 2011-03-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2019-08-25
    • 2019-09-10
    • 1970-01-01
    • 2016-12-14
    • 2020-08-05
    相关资源
    最近更新 更多