4

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.

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
ZWL
  • 319
  • 2
  • 4
  • If one of the responses answered your question, please click the check-mark to accept the answer. You might take a look at [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers) – G5W Aug 06 '17 at 22:43

5 Answers5

8

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
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
5

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
thelatemail
  • 91,185
  • 12
  • 128
  • 188
3
unlist(lapply(1:4, function(i) c(rep(0,i),i)))
submartingale
  • 715
  • 7
  • 16
3

You can use rep() to create a sequence that has n + 1 of each value:

n <- 4
myseq <- rep(seq_len(n), seq_len(n) + 1)
# [1] 1 1 2 2 2 3 3 3 3 4 4 4 4 4

Then you can use diff() to find the elements you want. You need to append a 1 to the end of the diff() output, since you always want the last value.

c(diff(myseq), 1)
# [1] 0 1 0 0 1 0 0 0 1 0 0 0 0 1

Then you just need to multiply the original sequence with the diff() output.

myseq <- myseq * c(diff(myseq), 1)
myseq
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
2
# the sequence
s = 1:4

# create zeros vector
vec = rep(0, sum(s+1))

# assign the sequence to the corresponding position in the zeros vector
vec[cumsum(s+1)] <- s

vec
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4

Or to be more succinct, use replace:

replace(rep(0, sum(s+1)), cumsum(s+1), s)
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4
Psidom
  • 209,562
  • 33
  • 339
  • 356