有人能给我解释一下这一行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代码做了我想做的事情(按组分配最大值),但问题是这是如何完成的?
发布于 2013-01-12 22:15:21
拆分得到矢量中的值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返回修改后的向量。
发布于 2013-01-12 22:16:03
多亏了这条评论,答案在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
}https://stackoverflow.com/questions/14294052
复制相似问题