Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand numeric vector elements with constant (natural number)

Tags:

integer

r

vector

Given a vector v <- c(1, 10, 22) and a constant natural number say c <- 3 how can I expand v with integers in a window of size c. So the vector would become w (i.e. 1 is expanded three integers to each side, the integers -2, -1, 0, 1, 2, 3, 4) :

> w
 [1] -2 -1  0  1  2  3  4  7  8  9 10 11 12 13 19 20 21 22 23 24 25
like image 809
user3375672 Avatar asked Feb 06 '26 19:02

user3375672


2 Answers

Another approach is

c(t(sapply(-c:c, `+`, v)))
#[1] -2 -1  0  1  2  3  4  7  8  9 10 11 12 13 19 20 21 22 23 24 25

And this is more efficient for large v-vectors because the sapply loop iterates only over -c:c instead of every element of v. A simple comparison shows this:

set.seed(1)
v <- sample(1e6)
system.time(unlist( Map(`:`, v-c, v+c)))              # akrun 1
#       User      System verstrichen 
#      1.518       0.067       1.595 
system.time(c(sapply(v, function(x) (x-c):(x+c))))    # akrun 2
#       User      System verstrichen 
#      1.564       0.074       1.652 
system.time(c(t(sapply(-c:c, '+', v))))               # docendo
#       User      System verstrichen 
#      0.082       0.024       0.106 
system.time(c(mapply(seq, v-c, v+c)))                 # 989
#       User      System verstrichen 
#      7.132       0.123       7.292 
like image 140
talat Avatar answered Feb 08 '26 08:02

talat


We can use sapply

c(sapply(v, function(x) (x-c):(x+c)))
#[1] -2 -1  0  1  2  3  4  7  8  9 10 11 12 13 19 20 21 22 23 24 25

Or Map

unlist( Map(`:`, v-c, v+c))
like image 29
akrun Avatar answered Feb 08 '26 09:02

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!