理解"ave"函数的源代码

adn*_*bps 1 r

以下是R中"ave"函数的源代码:

function (x, ..., FUN = mean) 
{
    if (missing(...)) 
        x[] <- FUN(x)
    else {
        g <- interaction(...)
        split(x, g) <- lapply(split(x, g), FUN)
    }
    x
}
Run Code Online (Sandbox Code Playgroud)

我无法理解赋值"split(x,g)< - lapply(split(x,g),FUN)"是如何工作的.请考虑以下示例:

# Overview: function inputs and outputs
> x = 10*1:6
> g = c('a', 'b', 'a', 'b', 'a', 'b')
> ave(x, g)
[1] 30 40 30 40 30 40

# Individual components of "split" assignment
> split(x, g)
$a
[1] 10 30 50
$b
[1] 20 40 60
> lapply(split(x, g), mean)
$a
[1] 30
$b
[1] 40

# Examine "x" before and after assignment
> x
[1] 10 20 30 40 50 60
> split(x, g) <- lapply(split(x, g), mean)
> x
[1] 30 40 30 40 30 40
Run Code Online (Sandbox Code Playgroud)

问题:

•为什么赋值"split(x,g)< - lapply(split(x,g),mean)",直接修改x?"< - "总是修改函数的第一个参数,还是有其他规则?

•这项任务如何运作?"split"和"lapply"语句都失去了x的原始排序.它们也是长度2.你如何得到一个长度(x)的矢量与x的原始排序相匹配?

Ste*_*n F 5

这是一个棘手的问题.<-通常不会以这种方式工作.实际发生的是你没有打电话split(),你正在调用一个名为的替换函数split<-().分裂的文件说

[...]替换表格取代了与此类别相对应的值.unsplit逆转了分裂的效果.

另见这个答案