How can I create this special sequence?

I would like to create the following sequence of vectors.

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

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

+4
source share
5 answers

You can use rep()to create a sequence with n + 1each 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 items you need. You need to add 1to the end of the output diff(), 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 by the output diff().

myseq <- myseq * c(diff(myseq), 1)
myseq
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4
+3

, :

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

, , :

(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

, d :

d[!lower.tri(d)][-1L]
# [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4
+8

rep rbind :

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

2 , , . rep , , , .

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

, , 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
+2

Source: https://habr.com/ru/post/1683127/


All Articles