为每组数据帧中的行创建一个序号(计数器) [英] Create a sequential number (counter) for rows within each group of a dataframe

查看:33
本文介绍了为每组数据帧中的行创建一个序号(计数器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何在数据帧的每组中生成唯一的 ID 号?以下是一些按personid"分组的数据:

How can we generate unique id numbers within each group of a dataframe? Here's some data grouped by "personid":

personid date measurement
1         x     23
1         x     32
2         y     21
3         x     23
3         z     23
3         y     23

我希望为personid"定义的每个子集中的每一行添加一个具有唯一值的 id 列,始终以 1 开头.这是我想要的输出:

I wish to add an id column with a unique value for each row within each subset defined by "personid", always starting with 1. This is my desired output:

personid date measurement id
1         x     23         1
1         x     32         2
2         y     21         1
3         x     23         1
3         z     23         2
3         y     23         3

感谢您的帮助.

推荐答案

一些 dplyr 替代方案,使用方便的函数 row_numbern.

Some dplyr alternatives, using convenience functions row_number and n.

library(dplyr)
df %>% group_by(personid) %>% mutate(id = row_number())
df %>% group_by(personid) %>% mutate(id = 1:n())
df %>% group_by(personid) %>% mutate(id = seq_len(n()))
df %>% group_by(personid) %>% mutate(id = seq_along(personid))

<小时>

您也可以使用 splitstackshape 包中的 getanID.请注意,输入数据集以 data.table 的形式返回.


You may also use getanID from package splitstackshape. Note that the input dataset is returned as a data.table.

getanID(data = df, id.vars = "personid")
#    personid date measurement .id
# 1:        1    x          23   1
# 2:        1    x          32   2
# 3:        2    y          21   1
# 4:        3    x          23   1
# 5:        3    z          23   2
# 6:        3    y          23   3

这篇关于为每组数据帧中的行创建一个序号(计数器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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