简体   繁体   中英

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 .

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

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
unlist(lapply(1:4, function(i) c(rep(0,i),i)))

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
# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM