R 为什么这个简单的ave函数不起作用
我使用以下代码和数据:R 为什么这个简单的ave函数不起作用,r,R,我使用以下代码和数据: > 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 > > w
> 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
以下工作:
> unique(d$count)
[1] 1 4 14 8 15 10 20
> unique(d$year)
[1] 2000 2001 2002
t聚合、聚合和按工作:
> 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函数?这有点微妙,我认为最好的文档实际上是R语言定义中关于: 函数求值中发生的第一件事是匹配 对于实际的或提供的参数来说是正式的。这是由一个 三通流程:
比赛。请注意,如果f有点微妙,但再次尝试您的第一次尝试,但显式的FUN=sumwith(d,ave(count,list(year),FUN=sum))有效。谢谢为什么在“tapply”、“aggregate”和“by”do时不假定它是一个函数?
> 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