ZWL
ZWL

Reputation: 329

How can I create this special sequence?

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.

Upvotes: 4

Views: 737

Answers (5)

thelatemail
thelatemail

Reputation: 93938

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

Upvotes: 5

Rich Scriven
Rich Scriven

Reputation: 99371

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

Upvotes: 8

akuiper
akuiper

Reputation: 215117

# 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

Upvotes: 2

Joshua Ulrich
Joshua Ulrich

Reputation: 176718

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

Upvotes: 3

submartingale
submartingale

Reputation: 755

unlist(lapply(1:4, function(i) c(rep(0,i),i)))

Upvotes: 3

Related Questions