3 回答
TA贡献1921条经验 获得超9个赞
使用diff和cumsum:
paste0("Group_", cumsum(c(1, diff(x) != 0)))
#[1] "Group_1" "Group_1" "Group_1" "Group_2" "Group_2" "Group_2" "Group_3" "Group_4" "Group_4" "Group_5" "Group_5"
(如果您的值是浮点值,则可能必须避免!=使用,而是使用公差。)
TA贡献1811条经验 获得超5个赞
groupdata2中的group()可以使用l_starts方法根据组起点列表创建组。通过设置n为auto,它会自动查找组开始:
x <- c(1,1,1,2,2,2,3,2,2,1,1)
groupdata2::group(x, n = "auto", method = "l_starts")
## # A tibble: 11 x 2
## # Groups: .groups [5]
## data .groups
## <dbl> <fct>
## 1 1 1
## 2 1 1
## 3 1 1
## 4 2 2
## 5 2 2
## 6 2 2
## 7 3 3
## 8 2 4
## 9 2 4
## 10 1 5
## 11 1 5
还有一个differs_from_previous()函数可以找到与先前值相差某个阈值的值或值的索引。
# The values to start groups at
differs_from_previous(x, threshold = 1,
direction = "both")
## [1] 2 3 2 1
# The indices to start groups at
differs_from_previous(x, threshold = 1,
direction = "both",
return_index = TRUE)
## [1] 4 7 8 10
- 3 回答
- 0 关注
- 582 浏览
添加回答
举报