Creating a vector, sequential elements of which are repeated that many times as the corresponding values in neighbouring columns

Viewed 27

In the below sample data frame, the output vector should be [1] 1,1,1,2,1,1,1,2,2,3,3,3,4,5,5,5,5,1,1,2,3,3,3

P   N   N+1 N+2 N+3 N+4
2   3   1   1   2   1
5   3   2   3   1   4
3   2   1   3   4   5

Explanation:

  • Values in P dictates how far to the right side should the data frame values be read. The values in seq(P) should then get repeated that many times.
  • First value of P is 2, which means that in seq(2) (which is 1,2), the first element should be repeated 3 time, and second element should be repeated 1 time.
  • This is because P's value (2) indicates to read first two elements on it's right side. Those values on right side themselves indicate how many times the sequential elements of 2 should be repeated.
1 Answers

An option here would be to loop over the rows with apply MARGIN = 1, then, get the seq based on the first element i.e. 'P', replicate the sequence with the corresponding values of 'N' columns subsetted with that sequence

unlist(apply(df1, 1, function(x)  {
        i1 <- seq(x[1])
        rep(i1, x[-1][i1])
       }))

-output

#[1] 1 1 1 2 1 1 1 2 2 3 3 3 4 5 5 5 5 1 1 2 3 3 3

data

df1 <- structure(list(P = c(2L, 5L, 3L), N = c(3L, 3L, 2L), `N+1` = c(1L, 
2L, 1L), `N+2` = c(1L, 3L, 3L), `N+3` = c(2L, 1L, 4L), `N+4` = c(1L, 
4L, 5L)), class = "data.frame", row.names = c(NA, -3L))
Related