# How to use row number inside apply function in R

I want to process data frame as follows, where I want to get the sum of 2 vectors and append it to a data frame as a row vector. 2 vectors are row vector of considering row and column vector which start just below the considering row with a fixed length.

`````` data
A b1 b2 b3
1 2  2  2
2 3  3  3
3 4  4  4
4 5  5  5
5 6  6  6

output (expected)
A b1 b2 b3
1 4  5  6
2 6  7  8
3 8  9  -
4 10 -  -
5 -  -  -
``````

In the example if 1st row is considered, two vectors are

`````` row vector r- [2 2 2]
column vector c - [2,3,4]
``````

After getting the transpose of column vector I can add tow vectors and append it to a new data frame. This process must be done to all the rows.

Easiest way to do this is looping, but in R loops are not efficient, instead `apply` function can be used. However in this scenario, to do that need to know what is the current row number.

Is there a way to do this efficiently in R

r

answered 7 months ago G. Grothendieck #1

1) rollapply We can use `rollapply` to form the matrix of subvectors of `A` and then add that together with an initial column of zero to `m`. Note that we pad `A` with NA values so that the result of `rollapply` is the appropriate shape.

``````library(zoo)

m <- cbind(A = 1:5, b1 = 2:6, b2 = 2:6, b3 = 2:6)  # input matrix

nc1 <- ncol(m) - 1
A <- c(m[, 1], rep(NA, nc1))
cbind(0, rollapply(A[-1], nc1, c)) + m
``````

giving:

``````     A b1 b2 b3
[1,] 1  4  5  6
[2,] 2  6  7  8
[3,] 3  8  9 NA
[4,] 4 10 NA NA
[5,] 5 NA NA NA
``````

2) base This solution is similar but does not use any packages. The first two lines are the same as in (1).

``````nc1 <- ncol(m) - 1
A <- c(m[, 1], rep(NA, nc1))
cbind(0, embed(A[-1], nc1)[, seq(nc1, 1)]) + m
``````

giving:

``````     A b1 b2 b3
[1,] 1  4  5  6
[2,] 2  6  7  8
[3,] 3  8  9 NA
[4,] 4 10 NA NA
[5,] 5 NA NA NA
``````