applyルーベンスが正しく、の代わりに使用したい場合、および今日の以前の投稿と同じ表現にaggregate興味がある場合は、を使用できます。aggregatetapply
~ の全体的な意味は何ですか?
x=iris[,1:4]
names(x)<-c("x1","x2","x3","x4")
aggregate(x1+x2+x3+x4~x1,FUN=sum,data=x)
tapply((x$x1 + x$x2 + x$x3 + x$x4), x$x1, sum)
DWinの回答から追加sapplyおよび変更して編集し、上記とlapply同じ回答、およびtapply再
フォーマットされた機能を提供します。aggregaterapplyvapplytapplyby
with(x, sapply(split((x1 + x2 + x3 + x4), x1), sum))
with(x, lapply(split((x1 + x2 + x3 + x4), x1), sum))
with(x, rapply(split((x1 + x2 + x3 + x4), x1), sum))
with(x, tapply( (x1 + x2 + x3 + x4), x1 , sum))
with(x, vapply(split((x1 + x2 + x3 + x4), x1), sum, FUN.VALUE=1))
with(x, by((x1 + x2 + x3 + x4), x1, sum))
で同じ答えを得る方法がわかりませんmapply。さて、ここに1つの方法がありますが、それはかなりばかげています:
tapply(mapply(sum, x$x1 , x$x2 , x$x3 , x$x4), x$x1, sum)
最後に、apply(inside tapply) を使用して上記の他の行と同じ答えを得る方法を次に示します。
tapply(apply((x[,1:4]),1,sum),x$x1,sum)
最後に、投稿のステートメントaggregateと同じ回答を本当に返したい場合は、それが可能です。applyただし、行っているのは、個々の行をapplyステートメントで合計しているだけです。aggregateしたがって、次のように、Iris データ セットの各行に個別のグループがあると「だまして」考える必要があります。
x=iris[,1:4]
names(x)<-c("x1","x2","x3","x4")
apply.sums <- transform(x,"sum"=apply(x,MARGIN=1,FUN=sum))
my.factor <- seq(1, nrow(x))
ag.sums <- aggregate(x1+x2+x3+x4~my.factor,FUN=sum,data=x)
round(ag.sums[,2],2) == round(apply.sums[,5],2)