Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

r - Create a sequence from vectors with start and end positions

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].

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

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)
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Just replace vec1 and vec2 by f.start and f.end provided all(f.start<=f.end)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...