【问题标题】:Sequentially numbering within many row blocks of unequal length [duplicate]在许多长度不等的行块内按顺序编号[重复]
【发布时间】:2012-12-27 00:37:23
【问题描述】:

我的实际数据集由每个 id 的重复测量值组成,其中测量值的数量可能因人而异。一个简化的例子是:

dat <- data.frame(id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L))
dat
##    id
## 1   1
## 2   1
## 3   1
## 4   1
## 5   1
## 6   1
## 7   2
## 8   2
## 9   3
## 10  3
## 11  3

我试图通过id 变量对dat 行进行顺序编号。结果应该是:

dat
##    id s
## 1   1 1
## 2   1 2
## 3   1 3
## 4   1 4
## 5   1 5
## 6   1 6
## 7   2 1
## 8   2 2
## 9   3 1
## 10  3 2
## 11  3 3

你会怎么做?我尝试使用duplicated() 选择每个id 的最后一行,但这可能不是这样,因为它适用于整个列。

【问题讨论】:

标签: r


【解决方案1】:

使用ave()。第一项是您要应用该功能的项目;其他项目是您的分组变量,FUN 是您要应用的功能。详情请见?ave

transform(dat, s = ave(id, id, FUN = seq_along))
#    id s
# 1   1 1
# 2   1 2
# 3   1 3
# 4   1 4
# 5   1 5
# 6   1 6
# 7   2 1
# 8   2 2
# 9   3 1
# 10  3 2
# 11  3 3

如果您有一个大数据集或正在使用data.table 包,您可以使用“.N”,如下所示:

library(data.table)
DT <- data.table(dat)
DT[, s := 1:.N, by = "id"]
## Or
## DT[, s := sequence(.N), id][]

或者,你可以使用rowid,像这样:

library(data.table)
setDT(dat)[, s := rowid(id)][]
#     id s
#  1:  1 1
#  2:  1 2
#  3:  1 3
#  4:  1 4
#  5:  1 5
#  6:  1 6
#  7:  2 1
#  8:  2 2
#  9:  3 1
# 10:  3 2
# 11:  3 3

为了完整起见,这里是“tidyverse”方法:

library(tidyverse)
dat %>% 
  group_by(id) %>% 
  mutate(s = row_number(id))
## # A tibble: 11 x 2
## # Groups: id [3]
##       id     s
##    <int> <int>
##  1     1     1
##  2     1     2
##  3     1     3
##  4     1     4
##  5     1     5
##  6     1     6
##  7     2     1
##  8     2     2
##  9     3     1
## 10     3     2
## 11     3     3

【讨论】:

  • 非常感谢,我不知道这个策略
【解决方案2】:
dat <- read.table(text = "
    id          
    1 
    1 
    1 
    1 
    1 
    1 
    2 
    2 
    3 
    3 
    3", 
header=TRUE)

data.frame(
    id = dat$id,
    s = sequence(rle(dat$id)$lengths) 
)

给予:

   id s
1   1 1
2   1 2
3   1 3
4   1 4
5   1 5
6   1 6
7   2 1
8   2 2
9   3 1
10  3 2
11  3 3

【讨论】:

    【解决方案3】:

    使用tapply,但不如ave优雅

     cbind(dat$id,unlist(tapply(dat$id,dat$id,seq_along)))
      [,1] [,2]
    11    1    1
    12    1    2
    13    1    3
    14    1    4
    15    1    5
    16    1    6
    21    2    1
    22    2    2
    31    3    1
    32    3    2
    33    3    3
    

    【讨论】:

    • 如果您查看ave() 的函数,您会发现它包含your question from earlier today ;)
    • @AnandaMahto 谢谢,但我知道。你在大街上比我快,我最后一分钟换了。
    猜你喜欢
    • 2018-01-26
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 2018-08-20
    • 2016-10-26
    • 2018-08-20
    • 2013-03-22
    • 1970-01-01
    相关资源
    最近更新 更多