[R] c(1:n, 1:(n-1), 1:(n-2), ... , 1)

Dan D ddalthorp at usgs.gov
Thu Sep 17 21:53:35 CEST 2015

Very nice variety of solutions to create c(1:n, 1:(n-1), 1:(n-2), ... , 1)

#Testing the methods with n=1000 (microbenchmark)

# by far the nicest-looking, easiest to follow, and fastest is Frank
# it also requires the minimum amount of memory (as do several of the
# 2.73 milliseconds (1x)

# not nearly as nice-looking but almost as fast:
# 2.82 milliseconds (1.03x)
do.call(c, lapply(n:1, function(n1) 1:n1)) 

# an improvement on look but 5x slower than do.call is:
# 13.3 milliseconds  (4.9x)
unlist(lapply(n:1, seq))

## the others are uglier and way slower [uses a full (n+1) x (n+1) matrix]
# 60.8 milliseconds (22.3x)
outer( 1:(n+1), 1:(n+1), '-')[ outer( 1:n, 1:(n+1), '>')]

# 71.8 milliseconds (26.3x) [uses a full (n x n) matrix]

# 421.3 milliseconds (154x)
Reduce( function(x,y){c( 1:y, x)}, 1:n)

# 3200 milliseconds (1170x)
cc<-0; # establish result as numeric
for(i in seq(n,1,-1)){ cc<-c(cc,seq(1,i)); str(cc); }; #generate array
    cc<-cc[2:length(cc)]; #remove the leading 0
} # 

# crashes:
mklist <- function(n) { 
     if (n==1) return(1) else return( c(seq(1,n),mklist(n-1)) ) 

View this message in context: http://r.789695.n4.nabble.com/c-1-n-1-n-1-1-n-2-1-tp4712390p4712399.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list