从R中的数字向量创建索引

时间:2017-08-04 14:59:06

标签: r indexing

我有一个长度的矢量,

lens <- c(3,4,6,8)   

我想从这个向量创建索引,它表示每个索引中索引的总数。期望输出将是1:3,4:7,8:13,14:21。如果是表的形式,它将是

start_idx    end_idx
1            3   #length of index is from length vector
4            7
8            13
14           21

1 个答案:

答案 0 :(得分:2)

似乎你需要cumsum

end_idx <- cumsum(lens)
start_idx <- c(0, head(end_idx,-1)) + 1

data.frame(start_idx, end_idx)

#  start_idx end_idx
#1         1       3
#2         4       7
#3         8      13
#4        14      21