R - 根据每次将另一列中的条件重置为 1 创建一列 ID

R - Creating a column of IDs based on each time the condition within another column resets to 1

我有一个数据框,其中包含物种种群及其在每个种群中的丰度。我想添加另一列,其中包含每个物种的 ID。种群列从 1 向上增加,并在每次出现新物种时重新设置。因此,物种 ID 列将沿着物种种群列计数,并且每次种群列重置为“1”时,值都会增加 +1。

我明白我要实现的原理,但是一直没能得到正确的结果。我在下面包含一个虚拟示例,其中包含 2 个物种的种群和计数:

df <- data.frame(Count=c(10, 5, 4, 10, 6),
                 Population=c(1, 2, 3, 1, 2))

Count Population
    10          1
     5          2
     4          3
    10          1
     6          2

期望的结果是:

Count Population species
  10          1       1
   5          2       1
   4          3       1
  10          1       2
   6          2       2 

根据每次 df$Population 中的值重置为 1 生成新的物种 ID 列。实际上,数据集包含数百个物种,每个物种的种群数量各不相同。

提前感谢您提出任何建议。如果问题或示例不清楚,请提前致歉。

麦克

几乎可以肯定有一种更优雅的方法可以做到这一点,但以下方法对我有用:

df <- data.frame(Count=c(10, 5, 4, 10, 6),
             Population=c(1, 2, 3, 1, 2))
df$species <- ifelse(df$Population==1,1,0)

counter1 <- 0
counter2 <- 1
for(i in 1:nrow(df)){
            if(df$species[i]==counter2){
                            df$species[i] <- df$species[i] + counter1
                            counter1 <- counter1 + 1}
            else (next) }
df

for(i in 2:nrow(df)){
            if(df$species[i]==0){
            df$species[i] <- df$species[i-1]
            } else (next)
}
df