【问题标题】:How to assign a unique ID number to each group of identical values in a column [duplicate]如何为列中的每组相同值分配唯一的ID号[重复]
【发布时间】:2014-06-09 11:44:33
【问题描述】:

我有一个包含许多列的数据框。我想创建一个名为“id”的新列,它为“sample”列中的每组相同值提供一个唯一的 ID 号。

示例数据:

# dput(df)
df <- structure(list(index = 1:30, val = c(14L, 22L, 1L, 25L, 3L, 34L, 
35L, 36L, 24L, 35L, 33L, 31L, 30L, 30L, 29L, 28L, 26L, 12L, 41L, 
36L, 32L, 37L, 56L, 34L, 23L, 24L, 28L, 22L, 10L, 19L), sample = c(5L, 
6L, 6L, 7L, 7L, 7L, 8L, 9L, 10L, 11L, 11L, 12L, 13L, 14L, 14L, 
15L, 15L, 15L, 16L, 17L, 18L, 18L, 19L, 19L, 19L, 20L, 21L, 22L, 
23L, 23L)), .Names = c("index", "val", "sample"), class = "data.frame", 
row.names = c(NA, -30L))

head(df)
  index val sample 
1     1  14      5  
2     2  22      6  
3     3   1      6  
4     4  25      7  
5     5   3      7  
6     6  34      7  

我想得到什么结果:

  index val sample id
1     1  14      5  1
2     2  22      6  2
3     3   1      6  2
4     4  25      7  3
5     5   3      7  3
6     6  34      7  3

【问题讨论】:

  • dplyr 解决方案:df$id &lt;- group_indices(df$sample).

标签: r dataframe unique


【解决方案1】:

怎么样

df2 <- transform(df,id=as.numeric(factor(sample)))

?

我认为这个(抄自Add ID column by group)应该稍微高效一些,虽然可能有点难记:

df3 <- transform(df, id=match(sample, unique(sample)))
all.equal(df2,df3)  ## TRUE

如果你想在 tidyverse 中这样做:

library(dplyr)
df %>% group_by(sample) %>% mutate(id=cur_group_id())

【讨论】:

  • 喜欢它:factors 的用途,我能理解。 :-)
  • 这里只是一个小提示:as.numeric(factor(sample)) 方法只会在 sample 已经排序的情况下产生降序数字序列。
  • factor() 解决方案的好处在于它忽略了NA
  • @Ben Bolker,谢谢!你能用dplyr写你的代码吗?
  • 你看到上面stackoverflow.com/questions/24119599/…的评论了吗?
【解决方案2】:

这是data.table 解决方案

library(data.table)
setDT(df)[, id := .GRP, by = sample]

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2017-12-18
    • 2018-10-07
    • 1970-01-01
    相关资源
    最近更新 更多