Mikhail Tsaplin - 5 months ago 22

R Question

I have two vectors:

`startIdxes<-c(1, 5, 12, 22)`

endIdxes<-c(2, 9, 17, 25)

The vectors presents ranges e.g 1:2, 5:9 ...

How I can build index vector using this two vectors?

The index vector should be:

`> c(1:2, 5:9, 12:17, 22:25)`

[1] 1 2 5 6 7 8 9 12 13 14 15 16 17 22 23 24 25

Answer

We can use `Map`

to get the sequence between corresponding values in both `vector`

s and `unlist`

the `list`

output.

```
unlist(Map(`:`, startIdxes, endIdxes))
#[1] 1 2 5 6 7 8 9 12 13 14 15 16 17 22 23 24 25
```

The function `Map`

is

```
Map
function (f, ...)
{
f <- match.fun(f)
mapply(FUN = f, ..., SIMPLIFY = FALSE)
}
```

Another option is getting the difference between the two vectors, adding with the replicate of 'startIdxes' with the `sequence`

of difference, concatenate with the original 'startIdxes' and `sort`

.

```
i1 <- endIdxes - startIdxes
sort(c(startIdxes, rep(startIdxes, i1) + sequence(i1)))
#[1] 1 2 5 6 7 8 9 12 13 14 15 16 17 22 23 24 25
```