Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create this special sequence?

Tags:

r

sequence

seq

rep

I would like to create the following vector sequence.

0 1 0 0 2 0 0 0 3 0 0 0 0 4

My thought was to create 0 first with rep() but not sure how to add the 1:4.

like image 365
ZWL Avatar asked Nov 29 '22 08:11

ZWL


2 Answers

Create a diagonal matrix, take the upper triangle, and remove the first element:

d <- diag(0:4)
d[upper.tri(d, TRUE)][-1L]
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4

If you prefer a one-liner that makes no global assignments, wrap it up in a function:

(function() { d <- diag(0:4); d[upper.tri(d, TRUE)][-1L] })()
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4

And for code golf purposes, here's another variation using d from above:

d[!lower.tri(d)][-1L]
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4
like image 169
Rich Scriven Avatar answered Dec 15 '22 13:12

Rich Scriven


rep and rbind up to their old tricks:

rep(rbind(0,1:4),rbind(1:4,1))
#[1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4

This essentially creates 2 matrices, one for the value, and one for how many times the value is repeated. rep does not care if an input is a matrix, as it will just flatten it back to a vector going down each column in order.

rbind(0,1:4)
#     [,1] [,2] [,3] [,4]
#[1,]    0    0    0    0
#[2,]    1    2    3    4

rbind(1:4,1)
#     [,1] [,2] [,3] [,4]
#[1,]    1    2    3    4
#[2,]    1    1    1    1
like image 41
thelatemail Avatar answered Dec 15 '22 12:12

thelatemail