分组观察数 [英] Observation number by group

查看:29
本文介绍了分组观察数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 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:

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屋!

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