简体   繁体   中英

How to create a combined sequence of constant length but starting at different values in R?

If I have a vector:

c(17,18,19)

And I want to get

c(17:17+5, 18:18+5, 19:19+5)

Or in other words:

c(17, 18, 19, 20, 21, 22, 18, 19, 20, 21, 22, 23, 19, 20, 21, 22, 23, 24)

How would I accomplish this in one line? Perhaps an essential R function I am missing? This can be done by sapply I am sure, but wondering if there was a non-iteration method.

c(outer(0:5, x, `+`))

要么

rep(x, each = 6) + rep(0:5, 3)

There are probably a few easier ways, but here's an mapply method.

> x <- c(17,18,19)
> c(mapply(seq, from = x, to = x + 5))
# [1] 17 18 19 20 21 22 18 19 20 21 22 23 19 20 21 22 23 24

Or even quicker

> c(mapply(`:`, from = x, to = x + 5))

mapply is basically a multi-apply , for applying a function to multiple vector or list arguments.

The following actually proved slightly faster than mapply

> c(sapply(x, function(y) `:`(y, y+5)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM