以下是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的原始排序相匹配?
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |