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.
0
rep()
1:4
You can use rep()to create a sequence with n + 1each value:
n + 1
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.
diff()
1
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
, :
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
d[!lower.tri(d)][-1L] # [1] 0 1 0 0 2 0 0 0 3 0 0 0 0 4
rep rbind :
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
unlist(lapply(1:4, function(i) c(rep(0,i),i)))
# 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
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
Source: https://habr.com/ru/post/1683127/More articles:How to use Butterknife new butterknife.debuggable option? - androidPriority array sorting - sortingUnderstanding __call__ with metaclasses - pythonCheck for template function availability - c ++Increase filter search width on FooTable Plugin - javascriptAVR C ++ uint32_t weird behavior - c ++Android VoIP application: PARTIAL_WAKE_LOCK against ignoring battery optimization ("white list of doses") - android-wake-lockКогда модульная система Java 9 интегрируется в Maven, как обрабатывать автоматический модуль - mavenOperator F # does not resolve correctly - operator-overloadingLaser timer function settings through application settings - azureAll Articles