gpt4 book ai didi

r - 如何为列中每组相同值分配唯一的 ID 号

转载 作者:行者123 更新时间:2023-12-03 07:36:34 33 4
gpt4 key购买 nike

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

示例数据:

df <- data.frame(
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
)
)

我想要的结果是:

  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

最佳答案

怎么样

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())

关于r - 如何为列中每组相同值分配唯一的 ID 号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24119599/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com