如何制作像1:n,1:(n-1),...... 1:2,1的序列?

问题描述 投票:1回答:2

n是一个整数。我想要的顺序是:

1:n, 1:(n-1), 1:(n-2), ... , 1:3, 1:2, 1

编者注:

在R中,1:n-11:(n-1)不同。小心。

r vector sequence seq
2个回答
5
投票

sequence(n:1)一样短。

sequence(4:1)
#[1] 1 2 3 4 1 2 3 1 2 1

这个功能并不神秘。

function (nvec) 
unlist(lapply(nvec, seq_len))

所以snoram's answer重新发明了轮子。但是调用seq_len比调用其他选项更快,因为它只是一个参数的原始函数(C函数)。

sequence2 <- function (nvec) unlist(lapply(nvec, seq.int, from = 1))
sequence3 <- function (nvec) unlist(lapply(nvec, function(x) 1:x))
sequence4 <- function (nvec) unlist(lapply(nvec, seq.default, from = 1))
sequence5 <- function (nvec) unlist(lapply(nvec, seq, from = 1))

library(microbenchmark)
microbenchmark(sequence(100:1), sequence2(100:1),
               sequence3(100:1), sequence4(100:1), sequence5(100:1))
#Unit: microseconds
#             expr     min        lq      mean    median        uq      max
#  sequence(100:1)  93.292  160.9325  205.5617  173.1995  200.0005 1157.201
# sequence2(100:1) 117.625  226.2120  308.4929  248.1055  280.8625 5477.710
# sequence3(100:1) 126.289  233.7875  365.6455  268.0495  301.8860 8808.911
# sequence4(100:1) 606.301 1195.4795 1463.3400 1237.5580 1344.3145 9986.619
# sequence5(100:1) 944.099 1864.3920 2063.3712 1942.2240 2119.3930 8581.593

## speed comparison
    seq     <  seq.default  <  function(x) 1:x  <  seq.int  <       seq_len
s3 generic       normal      light-weighted user  primitive   1-argument primitive

1
投票

也许李哲源的解决方案不会得到改善。但只是出于好奇,一个非常普遍的R'ish方式将是这样的:

unlist(lapply(4:1, function(x) 1:x))
[1] 1 2 3 4 1 2 3 1 2 1
© www.soinside.com 2019 - 2024. All rights reserved.