【问题标题】:why this simple ave function is not working为什么这个简单的 ave 函数不起作用
【发布时间】:2014-10-05 01:56:07
【问题描述】:

我正在使用以下代码和数据:

> d <- data.frame(year = rep(2000:2002, each = 3), count = round(runif(9, 0, 20)))
> d
  year count
1 2000     1
2 2000     4
3 2000     4
4 2001    14
5 2001     8
6 2001    15
7 2002    10
8 2002    14
9 2002    20
> 
> with(d, ave(count, year, sum))
Error in unique.default(x) : unique() applies only to vectors

我试过了:

> with(d, ave(count, list(year), sum))
Error in unique.default(x) : unique() applies only to vectors
> with(d, ave(count, list('year'), sum))
Error in unique.default(x) : unique() applies only to vectors
> 
> with(d, ave(count, 'year', sum))
Error in unique.default(x) : unique() applies only to vectors

> with(d, ave('count', 'year', sum))
Error in unique.default(x) : unique() applies only to vectors
> ave(d$count, d$year, sum)
Error in unique.default(x) : unique() applies only to vectors

> ave(d$count, factor(d$year), sum)
Error in unique.default(x) : unique() applies only to vectors

> ave(d$count, unique(d$year), sum)
Error in unique.default(x) : unique() applies only to vectors

> ave(d$count, factor(unique(d$year)), sum)
Error in unique.default(x) : unique() applies only to vectors
> ave(d$count, as.factor(unique(d$year)), sum)
Error in unique.default(x) : unique() applies only to vectors

以下作品:

> unique(d$count)
[1]  1  4 14  8 15 10 20
> unique(d$year)
[1] 2000 2001 2002

应用、汇总和按工作:

> with(d, tapply(count, year, mean))
    2000     2001     2002 
 3.00000 12.33333 14.66667 

> with(d, aggregate(count, list(year), mean))
  Group.1        x
1    2000  3.00000
2    2001 12.33333
3    2002 14.66667

> with(d, by(count, year, mean))
year: 2000
[1] 3
------------------------------------------------------------------------------------------------- 
year: 2001
[1] 12.33333
------------------------------------------------------------------------------------------------- 
year: 2002
[1] 14.66667

为什么会出现错误'unique() 仅适用于向量',我如何在这里使用 ave 函数?

【问题讨论】:

  • 这有点微妙,但请再次尝试您的第一次尝试,但使用明确的 FUN = sum
  • with(d, ave(count, list(year), FUN=sum)) 有效。谢谢。为什么它不假设它是一个函数,而 'tapply'、'aggregate' 和 'by' 做呢?

标签: r


【解决方案1】:

这有点微妙,我认为最好的文档实际上是在argument matching 上的 R 语言定义中:

在函数求值中发生的第一件事是匹配 对实际或提供的论点的形式。这是由一个 三道工序:

  1. 标签的精确匹配。对于每个命名提供的参数,列表 搜索形式参数以查找名称完全匹配的项目。 相同的形式参数匹配多个实际值是错误的 反之亦然。

  2. 标签的部分匹配。每个剩余的命名提供 使用部分将参数与剩余的形式参数进行比较 匹配。如果提供的参数的名称与 形式论点的第一部分,那么这两个论点是 被认为是匹配的。有多个部分是错误的 火柴。请注意,如果 f

  3. 位置匹配。任何 不匹配的形式参数绑定到未命名的提供参数,在 命令。如果有一个“...”参数,它将占用剩余的 参数,标记与否。

所以这是 参数的特殊性质的结果。从某种意义上说,它是“贪婪的”,除非您更明确并使用命名参数。这不会在其他地方弹出的原因是因为 通常是最后一个(或几乎是最后一个)参数,因此在使用位置匹配时您不会经常遇到这种令人困惑的行为。

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 2015-01-09
    • 2011-10-25
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多