Skip to content

Use as.numeric(seq_len(n)) in favor of seq(1, n) #1427

Closed
@krlmlr

Description

@krlmlr

What happens, and what did you expect instead?

#1330 (comment)

We also need the by argument to ensure that the output is a numeric.

Perhaps add a function seq_numeric() that has a special case for zero-length output?

To reproduce

seq(by = 1) seems to be the fastest, look at the units. Maybe it's worth arguing with R core to support seq(start, start - by, by) without error and to return an empty vector in this case?

x <- seq(1, 1, 1)
class(x)
#> [1] "numeric"
x
#> [1] 1
seq(1, 0, 1)
#> Error in seq.default(1, 0, 1): wrong sign in 'by' argument
bench::mark(
  sum(seq(1, 100000, 1)),
  sum(as.numeric(rlang::seq2(1, 100000))),
  sum(as.numeric(seq_len(100000)))
)
#> # A tibble: 3 × 6
#>   expression                             min median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr>                           <bch> <bch:>     <dbl> <bch:byt>    <dbl>
#> 1 sum(seq(1, 1e+05, 1))                628µs  791µs     1233.    1.91MB     46.8
#> 2 sum(as.numeric(rlang::seq2(1, 1e+05… 861ns  984ns   898993.        0B      0  
#> 3 sum(as.numeric(seq_len(1e+05)))      164ns  246ns  3139792.        0B    314.

Created on 2024-07-05 with reprex v2.1.0

System information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions