How to create an incremental vector which appends row-wise the values of first N columns using vector operation

Viewed 31

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

P   N   N+1 N+2 N+3 N+4
2   1   2   3   4   5
3   6   7   8   9   10
2   8   5   7   6   5
5   4   3   2   1   9
2   7   1   1   1   1

Explanation: Values in P dictates how far to the right side should the data frame values be read and appended into the final vector. 2 means, first two values to the right should be read which gives [1] 1,2

If possible, please tell how to do it with and without explicit loop operations. Thanks!

2 Answers

We can use apply with MARGIN = 1 to loop over the rows, use the first value as index (x[1]), get the sequnece of it, subset the elements in rows without the first element and subset based on the position index from seq, then unlist the list to create the vector

unname(unlist(apply(df1, 1, function(x) x[-1][seq(x[1])])))
#[1] 1 2 6 7 8 8 5 4 3 2 1 9 7 1

data

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

With loops

dummy data:

df = numeric()
for(i in 1:5){
  df = cbind(df, sample(1:5,5))}

> df
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    2    3    5
[2,]    1    4    5    2    1
[3,]    2    5    1    4    2
[4,]    5    1    3    1    4
[5,]    4    2    4    5    3

We append vec with the i'th row, from the 2'nd column until the "P'th" (given by df[i,1]) column:

vec = numeric()
for(i in 1:nrow(df)){
  vec = c(vec, df[i,2:(df[i,1])])}


> vec
 [1] 3 2 4 1 5 1 3 1 4 2 4 5
Related