Home > OS >  Adding the subsequent numbers of list containing random numbers, to the subsequent indices
Adding the subsequent numbers of list containing random numbers, to the subsequent indices

Time:11-11

I have a list with some random numbers. I want to add the two following numbers for each random number and add them to the subsequent indices in the list, without using a for loop.

So, lets say I have this list: v <- c(238,1002,569,432,6,1284) Then the output I want is: v <- c(238,239,240,1002,1003,1004,569,570,571,432,433,434,6,7,8,1284,1285,1286)

I am still pretty new to r, so I don't really know what I'm doing, but I've tried for hours now with no results.. I have tho, made it work using a for loop, but I know r isn't too happy with loops so I really need to vectorize it, somehow.

Does anybody know how I can implement this into my r code in an efficient manner?

CodePudding user response:

You can just use outer to calculate the outer sum:

res <- outer(0:2, v, " ")
#     [,1] [,2] [,3] [,4] [,5] [,6]
#[1,]  238 1002  569  432    6 1284
#[2,]  239 1003  570  433    7 1285
#[3,]  240 1004  571  434    8 1286

You can then turn the resulting matrix into a vector:

res <- as.vector(res)
#[1]  238  239  240 1002 1003 1004  569  570  571  432  433  434    6    7    8 1284 1285 1286

Note that matrices are "column-major" in R.

  • Related