将一个因子的计数添加到数据帧 [英] Adding counts of a factor to a dataframe

查看:95
本文介绍了将一个因子的计数添加到数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,每行是关于学生的观察。数据框架中的一个向量是学校的ID。我已经获得了一个新的矢量,每个学校的计数如下:

  tbsch<  -  table(dt $ school)

现在我想在 dt 。我已经使用 for()循环遍历 dt 中的每一行,并创建一个包含相关计数的新向量,最后使用 cbind()将其添加到 dt ,但我认为这是非常低效的。有没有一个聪明/简单的方法来做到这一点?

解决方案

使用jmsigner的数据可以做:

  dt $ count<  -  ave(dt $ school,dt $ school,FUN = length)
pre>

I have a data frame where each row is an observation concerning a pupil. One of the vectors in the data frame is an id for the school. I have obtained a new vector with counts for each school as follows:

tbsch <- table(dt$school)

Now I want to add the relevant count value to each row in dt. I have done it using for() looping through each row in dt and making a new vector containing the relevant count and finally using cbind() to add it to dt, but I think this is very inefficient. Is there a smart/easy way to do that ?

解决方案

using jmsigner's data you could do:

dt$count <- ave(dt$school, dt$school,  FUN = length)

这篇关于将一个因子的计数添加到数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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