Home > Mobile >  A vector is created from different vectors and i want to find starting and ending positions of these
A vector is created from different vectors and i want to find starting and ending positions of these

Time:03-08

These vectors will always be in increasing order such as 1 ..2 ... 3 ..4. They cannot decrease. Let's say I have three vectors as an example.

v1 <- c(1,3)
v2 <- c(2)
v3 <- c(1,3,4)

And I have a vector that was created from these vectors:

vsum <- c(v2, v1, v3)

Now i want to create a code which can find the position where each vector (v1,v2,v3) starts and ends in vsum. In this case, the starting position would look like

start <- c(1,2,4)

because if I run vsum these are the starting positions of each vector.

2 1 3 1 3 4

the ending position would look like

end <- c(1,3,6)

because these are ending positions

2 1 3 1 3 4

CodePudding user response:

You can wrap your vectors in a list and use lengths with cumsum:

v1 <- c(1,3)
v2 <- c(2)
v3 <- c(1,3,4)
l = lengths(list(v2, v1, v3))
# [1] 1 2 3

start = cumsum(l) - l   1
# [1] 1 2 4

end = cumsum(l)
# [1] 1 3 6
  • Related