创建连续值的组名

看起来很容易完成,无法找到更简单的方法。我在x下面有一个向量,需要为连续的值创建组名。我的尝试是使用rle,更好的主意?


# data

x <- c(1,1,1,2,2,2,3,2,2,1,1)


# make groups

rep(paste0("Group_", 1:length(rle(x)$lengths)), rle(x)$lengths)

# [1] "Group_1" "Group_1" "Group_1" "Group_2" "Group_2" "Group_2" "Group_3" "Group_4"

# [9] "Group_4" "Group_5" "Group_5"


至尊宝的传说
浏览 583回答 3
3回答

郎朗坤

使用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"(如果您的值是浮点值,则可能必须避免!=使用,而是使用公差。)

四季花海

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:&nbsp; &nbsp;.groups [5]##&nbsp; &nbsp; &nbsp;data .groups##&nbsp; &nbsp; <dbl> <fct>&nbsp;&nbsp;##&nbsp; 1&nbsp; &nbsp; &nbsp;1 1&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 2&nbsp; &nbsp; &nbsp;1 1&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 3&nbsp; &nbsp; &nbsp;1 1&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 4&nbsp; &nbsp; &nbsp;2 2&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 5&nbsp; &nbsp; &nbsp;2 2&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 6&nbsp; &nbsp; &nbsp;2 2&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 7&nbsp; &nbsp; &nbsp;3 3&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 8&nbsp; &nbsp; &nbsp;2 4&nbsp; &nbsp; &nbsp;&nbsp;##&nbsp; 9&nbsp; &nbsp; &nbsp;2 4&nbsp; &nbsp; &nbsp;&nbsp;## 10&nbsp; &nbsp; &nbsp;1 5&nbsp; &nbsp; &nbsp;&nbsp;## 11&nbsp; &nbsp; &nbsp;1 5&nbsp; &nbsp; &nbsp;还有一个differs_from_previous()函数可以找到与先前值相差某个阈值的值或值的索引。# The values to start groups atdiffers_from_previous(x, threshold = 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; direction = "both")## [1] 2 3 2 1# The indices to start groups atdiffers_from_previous(x, threshold = 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; direction = "both",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return_index = TRUE)## [1] 4 7 8 10
打开App,查看更多内容
随时随地看视频慕课网APP