如何将自定义结果添加到现有的数据框架 [英] How to add tapply results to an existing data frame

查看:101
本文介绍了如何将自定义结果添加到现有的数据框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将点击结果添加到原始数据框中作为新列。

I would like to add tapply results to the original data frame as a new column.

这里是我的数据框架:

 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)得到每个类别的平均值,但是我没有找到一种方法来添加它数据集在这样一个新的列我将具有相关类别的平均值。

I would like to to add the mean of each category to the data frame as a column. I used: tapply(dat$birds, dat$category, mean) to get the mean per category but I didn't find a way to add it to the data set in such away that in a new column I'll have the mean of the relevant category.

推荐答案

你可以使用 ave base

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

如果您要使用,请点击

  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 这将是快速

Or you can use data.table which would be fast

 library(data.table)
 setDT(dat)[,mbirds1:= mean(birds), by=category]

这篇关于如何将自定义结果添加到现有的数据框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆