Generate an incrementally increasing sequence like 112123123412345
Use sequence
:
> sequence(1:5)
[1] 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
Fastest way to make expanding sequence
You can do
sequence(1:n)
It is short and beats everything else... (so far). I also find
sequence(sequence(n))
somewhat satisfying. It is the same speedwise.
How to create an vector with incremental values based on values of another vector?
You can use sequence
to generate the numbers.
sequence(v1)
# [1] 1 2 3 4 5 6 7 1 2 3 4 5 6 1 2 3 4 5
And with a loop using lapply
:
unlist(lapply(v1, seq))
How can I remove one number each time while replicating a number of sequence in r?
I am sure there is a fancier way, but the following code achieves the goal in base R.
out = integer()
a = 2:6
while( length(a) > 1 ) {
a = a[-length(a)]
out = c(out, a)
}
out
#> [1] 2 3 4 5 2 3 4 2 3 2
Created on 2021-03-18 by the reprex package (v1.0.0)
Generate sequence (1,301,2, 302, 3, 303, 4,304 ...) in R
Use rbind
to alternate between the values
as.vector(rbind(1:300, 301:600))
Generate series 1, 2,1, 3,2,1, 4,3,2,1, 5,4,3,2,1
With sequence
:
rev(sequence(5:1))
# [1] 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1
From R 4.0.0 sequence
takes arguments from
and by
:
sequence(1:5, from = 1:5, by = -1)
# [1] 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1
Far from the golf minimalism of rev
... However, if you wake up one morning and want to create such a sequence with n = 1000 (like in the answer below), the latter is in fact faster (but I can hear Brian Ripley in fortunes::fortune(98)
)
n = 1000
microbenchmark(
f_rev = rev(sequence(n:1)),
f_seq4.0.0 = sequence(1:n, from = 1:n, by = -1))
# Unit: microseconds
# expr min lq mean median uq max neval
# f_rev 993.7 1040.3 1128.391 1076.95 1133.3 1904.7 100
# f_seq4.0.0 136.4 141.5 153.778 148.25 150.1 304.7 100
generate increasing sequence in R
Try:
rep(1:62,each=96)
length(rep(1:62,each=96))
[1] 5952
Related Topics
Dplyr Mutate with Conditional Values
Select Every Other Element from a Vector
How to Remove an Element from a List
Fill and Border Colour in Geom_Point (Scale_Colour_Manual) in Ggplot
How to Add Legend to Ggplot Manually? - R
How to Overlay Density Plots in R
Date Conversion from Posixct to Date in R
How Do Keep Only Unique Words Within Each String in a Vector
Position of the Sun Given Time of Day, Latitude and Longitude
Check for Installed Packages Before Running Install.Packages()
Extract Matrix Column Values by Matrix Column Name
R Shiny: Reactivevalues VS Reactive
Alternative to Expand.Grid for Data.Frames
How to Make Tibbles Display Significant Digits
How to Specify the Actual X Axis Values to Plot as X Axis Ticks in R