【发布时间】: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