我收到了一位同事的一些数据,他正在处理记录在几条横断面上的动物观察。但是,我的同事使用相同的三个ID代码来识别每个横断面: 1、7、13和19。我想用唯一的ID替换重复的ID。这张图片显示了我想要做的事情:

以下是相应的代码:
example_data<-structure(list(ID_Transect = c(1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L,
7L, 7L, 7L, 7L, 13L, 13L, 13L, 13L, 13L, 13L, 19L, 19L, 19L,
19L, 19L, 19L, 1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L),
transect_id = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L)), class = "data.frame", row.names = c(NA,
-36L))发布于 2021-06-18 10:25:43
你可以用data.table rleid -
example_data$transect_id <- data.table::rleid(example_data$ID_Transect)
#[1] 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 4 5 5 5 5 5 5 6 6 6 6 6 6在R基中,我们可以使用rle -
with(rle(example_data$ID_Transect), rep(seq_along(values), lengths))或者diff + cumsum -
cumsum(c(TRUE, diff(example_data$ID_Transect) != 0))发布于 2021-06-18 16:48:48
我们也可以
library(data.table)
setDT(example_data)[, transect_id := rleid(ID_Transect)]https://stackoverflow.com/questions/68033379
复制相似问题