创建新的重复索引,其中每个数字的范围尽可能高效地依赖于另一列的索引
Create new repeating index where range of each number is dependent on the index of another column as efficiently as possible
我有一个数字向量。
initialindex= c(17, 23, 28, 34, 39, 45)
我想从中得到的是这样的:
finalindex=c(1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5)
数字根据initialindex的不同重复。 23-17= 6 个 1 和 28-23= 5'2。
我可以获取初始索引的差异:
diff(initialindex)
这将给出最终索引中每个值的长度(6 个 1、5 个 2、6 个 3)。但是,然后我需要用新的索引值 1 复制它们: len(initialindex)
谁能帮我解决这个问题?
特蕾西
一个选项可以是:
cumsum(sequence(diff(initialindex)) == 1)
[1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
使用inverse.rle
x <- rle(0)
x$lengths <- diff(initialindex)
x$values <- seq_along(x$lengths)
inverse.rle(x)
[1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
使用rep
的解决方案——最初由@gung - Reinstate Monica提出但被删除
rep(x = 1:(length(initialindex) - 1L),
times = diff(initialindex))
# [1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
我有一个数字向量。
initialindex= c(17, 23, 28, 34, 39, 45)
我想从中得到的是这样的:
finalindex=c(1,1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5)
数字根据initialindex的不同重复。 23-17= 6 个 1 和 28-23= 5'2。
我可以获取初始索引的差异:
diff(initialindex)
这将给出最终索引中每个值的长度(6 个 1、5 个 2、6 个 3)。但是,然后我需要用新的索引值 1 复制它们: len(initialindex)
谁能帮我解决这个问题?
特蕾西
一个选项可以是:
cumsum(sequence(diff(initialindex)) == 1)
[1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
使用inverse.rle
x <- rle(0)
x$lengths <- diff(initialindex)
x$values <- seq_along(x$lengths)
inverse.rle(x)
[1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5
使用rep
的解决方案——最初由@gung - Reinstate Monica提出但被删除
rep(x = 1:(length(initialindex) - 1L),
times = diff(initialindex))
# [1] 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5