为给定嵌套变量的出现创建编号序列 [英] Create numbered sequence for occurrences of a given nesting variable

查看:47
本文介绍了为给定嵌套变量的出现创建编号序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望向数据集中添加一个变量,该变量对出现某个分组变量的实例进行排序.例如:

I'm hoping to add to a data set a variable that sequences the instances a certain grouping variable appears. For example:

ids <- c(rep(1,4),rep(2,6),rep(3,2))

我想要另一个变量来计算每个 id 出现的实例.像这样创建一个向量:

I'm wanting another variable that would count the instances each id appears. Creating a vector like this:

1,2,3,4,1,2,3,4,5,6,1,2

它们结合起来看起来像这样:

With them combined looking something like this:

    ids count
1    1      1
2    1      2
3    1      3
4    1      4
5    2      1
6    2      2
7    2      3
8    2      4
9    2      5
10   2      6
11   3      1
12   3      2

有什么想法吗?非常感谢!

Any ideas? Many thanks!

推荐答案

我建议 aveseq_along

ids <- c(rep(1,4),rep(2,6),rep(3,2))
count <- ave(ids,ids, FUN=seq_along)
cbind(ids, count)

#       ids count
#  [1,]   1     1
#  [2,]   1     2
#  [3,]   1     3
#  [4,]   1     4
#  [5,]   2     1
#  [6,]   2     2
#  [7,]   2     3
#  [8,]   2     4
#  [9,]   2     5
# [10,]   2     6
# [11,]   3     1
# [12,]   3     2

这篇关于为给定嵌套变量的出现创建编号序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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