分组观察次数 [英] Observation number by group
本文介绍了分组观察次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 R 中,我有一个数据框,其中包含由多个值描述的观察结果,其中一个是一个因素.我已按此因子对数据集进行了排序,并希望添加一列,在该列中我将获得有关因子每个级别的一些观察结果,例如
In R I have a data frame with observations described by several values one of which is a factor. I have sorted the dataset by this factor and would like to add a column in which I would get a number of observation on each level of the factor e.g.
factor obsnum
a 1
a 2
a 3
b 1
b 2
b 3
b 4
c 1
c 2
...
在 SAS 中,我使用以下方法:
In SAS I do it with something like:
data logs.full;
set logs.full;
count + 1;
by cookie;
if first.cookie then count = 1;
run;
如何在 R 中实现这一点?
How can I achieve that in R?
谢谢,
推荐答案
使用rle
(运行长度编码)和sequence
:
Use rle
(run length encoding) and sequence
:
x <- c("a", "a", "a", "b", "b", "b", "b", "c", "c")
data.frame(
x=x,
obsnum = sequence(rle(x)$lengths)
)
x obsnum
1 a 1
2 a 2
3 a 3
4 b 1
5 b 2
6 b 3
7 b 4
8 c 1
9 c 2
这篇关于分组观察次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文