本文介绍了创建连续值的组名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
看起来很简单,却找不到简单的方法.我在下面有一个x
向量,需要为连续的值创建组名.我的尝试是使用rle
,更好的主意吗?
Looks like an easy task, can't figure out a simpler way. I have an x
vector below, and need to create group names for consecutive values. My attempt was using rle
, better ideas?
# 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"
推荐答案
使用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"
(如果您的值是浮点值,则可能必须避免使用!=
并改用公差).
(If your values are floating point values, you might have to avoid !=
and use a tolerance instead.)
这篇关于创建连续值的组名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!