![](/img/trans.png)
[英]Assign unique non-repeated ID to nested groups with the same values in R
[英]assign unique id based on each new instance of a value, and assign same ID to subsequent repeated values
希望在R中執行類似的操作,但是需要在每個新的“ 1”實例之后為后續的“ 0”值分配相同的值。 所以我的數據看起來像這樣:
Val
1
0
0
0
1
0
1
0
0
0
0
並且需要分配唯一的ID,如下所示:
Val ID
1 1
0 1
0 1
0 1
1 2
0 2
1 3
0 3
0 3
0 3
0 3
采用 -
df$ID <- cumsum(df$Val)
產量
Val ID
1 1 1
2 0 1
3 0 1
4 0 1
5 1 2
6 0 2
7 1 3
8 0 3
9 0 3
10 0 3
11 0 3
使用dplyr
和zoo
:
df %>%
group_by(Val) %>% #Grouping by Val
mutate(temp = ifelse(Val == 0, NA, sequence(n()))) %>% #Assigning NA if Val is zero, otherwise creating a sequence around the ones
ungroup() %>%
mutate(ID = na.locf(temp)) %>% #Filling the NAs with the last non-NA case
select(-temp)
Val ID
<int> <int>
1 1 1
2 0 1
3 0 1
4 0 1
5 1 2
6 0 2
7 1 3
8 0 3
9 0 3
10 0 3
11 0 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.