3

tapply結果を元のデータ フレームに新しい列として追加したいと考えています。

ここに私のデータフレームがあります:

 dat <- read.table(text = " category birds    wolfs     snakes
                   yes        3        9         7
                   no         3        8         4
                   no         1        2         8
                   yes        1        2         3
                   yes        1        8         3
                   no         6        1         2
                   yes        6        7         1
                   no         6        1         5
                   yes        5        9         7
                   no         3        8         7
                   no         4        2         7
                   notsure    1        2         3
                   notsure    7        6         3
                   no         6        1         1
                   notsure    6        3         9
                   no         6        1         1   ",header = TRUE)

各カテゴリの平均を列としてデータ フレームに追加したいと思います。カテゴリごとの平均を取得するために使用tapply(dat$birds, dat$category, mean)しましたが、新しい列に関連するカテゴリの平均が表示されるように、それをデータセットに追加する方法が見つかりませんでした。

4

3 に答える 3

6

aveからご利用いただけますbase

  dat$mbirds <- with(dat, ave(birds, category, FUN=mean))

使いたい場合tapply

  mbirds1 <- with(dat, tapply(birds, category, mean))
  dat$mbirds1 <- mbirds1[match(dat$category,names(mbirds1))]

  head(dat)
  #  category birds wolfs snakes mbirds mbirds1
 #1      yes     3     9      7  3.200   3.200
 #2       no     3     8      4  4.375   4.375
 #3       no     1     2      8  4.375   4.375
 #4      yes     1     2      3  3.200   3.200
 #5      yes     1     8      3  3.200   3.200
 #6       no     6     1      2  4.375   4.375

または、data.tableどちらが高速かを使用できます

 library(data.table)
 setDT(dat)[,mbirds1:= mean(birds), by=category]
于 2014-09-01T11:29:07.280 に答える
3

これがaggregate答えです。引数に数式を使用すると、簡単で便利になります。

> a <- aggregate(birds~category, dat, mean)
> cb <- cbind(dat, mean = a[,2][match(dat[[1]], a[,1])])
> head(cb)
#  category birds wolfs snakes  mean
#1      yes     3     9      7 3.200
#2       no     3     8      4 4.375
#3       no     1     2      8 4.375
#4      yes     1     2      3 3.200
#5      yes     1     8      3 3.200
#6       no     6     1      2 4.375
于 2014-09-01T12:12:02.480 に答える