てみby
(?by
)あなたはもっと複雑なことをやって起動する場合は、ベース・R.をしたい場合は、plyr
/dplyr
パッケージはかなり驚くべきものだ、とあなたは巨大なデータセットを周りマックしようとしている場合は、ビットを気にしません最初の学習曲線の多くは、data.table
パッケージも素晴らしいです。
reproducible exampleは素晴らしいでしょう。
など。
set.seed(1) # so your random numbers are the same as mine
pincome <- data.frame(incomechng = runif(20, min=-1, max=3))
# what you had was fine too; using ?cut is another way to do it
# have just put it in for demonstration purposes.
# though `cut` uses intervals like (a, b] or [a, b) whereas yours
# are (-Inf, 0] (0, 1) [1, Inf) which is a little different.
pincome$income_growth <- cut(pincome$incomechng,
breaks=c(-Inf, 0, 1, Inf),
labels=paste("level", 1:3))
ここで、各グループ内の平均を取ることができます。私は3つの選択肢を示しました。私はもっとあると確信しています。
# base R ?by
by(pincome$incomechng, pincome$income_growth, mean)
# pincome$income_growth: level 1
# [1] -0.6848674
# ------------------------------------------
# pincome$income_growth: level 2
# [1] 0.4132334
# ------------------------------------------
# pincome$income_growth: level 3
# [1] 1.772039
# plyr (dplyr has pipe syntax you may prefer but is otherwise the same)
library(plyr)
ddply(pincome, .(income_growth), summarize, avgIncomeGrowth=mean(incomechng))
# income_growth avgIncomeGrowth
# 1 level 1 -0.6848674
# 2 level 2 0.4132334
# 3 level 3 1.7720395
# data.table
library(data.table)
setDT(pincome)
pincome[, list(avgIncomeGrowth=mean(incomechng)), by=income_growth]
# income_growth avgIncomeGrowth
# 1: level 2 0.4132334
# 2: level 3 1.7720395
# 3: level 1 -0.6848674
私は正しい道を推測しているが、 '(DF、AVE(V、レベル))との'のようなものであるか、 '(DF、tapply(V、レベル))と'どこ 'DF'は、あなたのデータであり、 .frame、 'v'はあなたの変数、' level'はあなたのグループ変数です。詳細は、 '?ave'と'?tapply'と入力してください。 – Frank