将一个因子的计数添加到数据帧 [英] Adding counts of a factor to a dataframe
问题描述
tbsch< - table(dt $ school)
现在我想在 dt $中的每一行添加相关的计数值c $ c>。我已经使用
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 usingfor()
looping through each row indt
and making a new vector containing the relevant count and finally usingcbind()
to add it todt
, 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屋!