为数据帧的每个组中的行创建序列号(计数器) [英] Create a sequential number (counter) for rows within each group of a dataframe
本文介绍了为数据帧的每个组中的行创建序列号(计数器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在数据框架的每个组中生成唯一的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
推荐答案
错误地命名为 ave()
函数,参数 FUN = seq_along
会很好地完成 - 即使你的 personid
列不严格排序。
The misleadingly named ave()
function, with argument FUN=seq_along
, will accomplish this nicely -- even if your personid
column is not strictly ordered.
df <- read.table(text = "personid date measurement
1 x 23
1 x 32
2 y 21
3 x 23
3 z 23
3 y 23", header=TRUE)
## First with your data.frame
ave(df$personid, df$personid, FUN=seq_along)
# [1] 1 2 1 1 2 3
## Then with another, in which personid is *not* in order
df2 <- df[c(2:6, 1),]
ave(df2$personid, df2$personid, FUN=seq_along)
# [1] 1 1 1 2 3 2
这篇关于为数据帧的每个组中的行创建序列号(计数器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文