从具有起始和结束位置的向量创建序列 [英] Create a sequence from vectors with start and end positions
问题描述
给出两个相等长度的独立向量:f.start和f.end,我想构造一个序列(乘以1),从f.start[1]:f.end[1]
到f.start[2]:f.end[2]
,...,到f.start[n]:f.end[n]
.
Given two separate vectors of equal length: f.start and f.end, I would like to construct a sequence (by 1), going from f.start[1]:f.end[1]
to f.start[2]:f.end[2]
, ..., to f.start[n]:f.end[n]
.
这里是一个只有6行的示例.
Here is an example with just 6 rows.
f.start f.end
[1,] 45739 122538
[2,] 125469 202268
[3,] 203563 280362
[4,] 281657 358456
[5,] 359751 436550
[6,] 437845 514644
粗略地讲,循环可以做到这一点,但是对于较大的数据集(行> 2000)而言,循环非常慢.
Crudely, a loop can do it, but is extremely slow for larger datasets (rows>2000).
f.start<-c(45739,125469,203563,281657,359751,437845)
f.end<-c(122538,202268,280362,358456,436550,514644)
f.ind<-f.start[1]:f.end[1]
for (i in 2:length(f.start))
{
f.ind.temp<-f.start[i]:f.end[i]
f.ind<-c(f.ind,f.ind.temp)
}
我怀疑这可以通过apply()来完成,但是我还没有弄清楚如何在apply中包含两个单独的参数,因此希望能提供一些指导.
I suspect this can be done with apply(), but I have not worked out how to include two separate arguments in apply, and would appreciate some guidance.
推荐答案
您可以尝试使用mapply
或Map
,它们同时对两个向量进行迭代.您需要提供该函数作为第一个参数:
You can try using mapply
or Map
, which iterates simultaneously on your two vectors. You need to provide the function as first argument:
vec1 = c(1,33,50)
vec2 = c(10,34,56)
unlist(Map(':',vec1, vec2))
# [1] 1 2 3 4 5 6 7 8 9 10 33 34 50 51 52 53 54 55 56
只需将vec1
和vec2
替换为f.start
和f.end
(只要提供all(f.start<=f.end)
Just replace vec1
and vec2
by f.start
and f.end
provided all(f.start<=f.end)
这篇关于从具有起始和结束位置的向量创建序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!