nw.
nw.

Reputation: 5155

Creating a sequence bases on value of previous element

I'm trying to get 20 sequences of length 1000, each generated by randomly adding 1 or 0 to the previous element in the sequence.

I tried this:

h <- replicate(20, rep(0, 1000), simplify=FALSE)
lapply(h, function(v) for(i in 2:1000){ v[i] = v[i - 1] + 1 })

But the for loop in the lapply doesn't appear to do anything, and I'm left with a list of 20 lists of 1000 0s.

What is a working way to do this? If there's a way to do it without a loop, even better :)

Thanks

Upvotes: 0

Views: 88

Answers (1)

Blue Magister
Blue Magister

Reputation: 13363

set.seed(100)
x <- replicate(20, cumsum(sample(0:1, 1000, replace = TRUE)), simplify = FALSE)
str(x)
# List of 20
 # $ : int [1:1000] 0 0 1 1 1 1 2 2 3 3 ...
 # $ : int [1:1000] 0 0 1 2 2 2 2 2 3 4 ...
 # $ : int [1:1000] 1 2 3 3 4 5 6 6 7 7 ...
 # $ : int [1:1000] 0 0 1 1 2 2 3 4 4 5 ...
 # $ : int [1:1000] 1 1 1 2 2 2 2 3 3 3 ...
 # $ : int [1:1000] 1 2 2 3 4 5 6 7 7 7 ...
 # $ : int [1:1000] 0 0 0 1 2 3 3 4 5 6 ...
 # $ : int [1:1000] 1 1 1 2 3 3 4 4 4 5 ...
 # $ : int [1:1000] 1 1 1 1 1 1 1 1 1 2 ...
 # $ : int [1:1000] 1 1 2 3 3 3 3 3 3 3 ...
 # $ : int [1:1000] 1 1 1 1 2 3 3 4 4 5 ...
 # $ : int [1:1000] 0 0 1 1 1 2 3 3 3 4 ...
 # $ : int [1:1000] 0 0 1 1 1 2 2 3 4 4 ...
 # $ : int [1:1000] 0 0 1 1 2 2 3 4 4 4 ...
 # $ : int [1:1000] 0 0 1 2 2 2 2 3 3 3 ...
 # $ : int [1:1000] 1 2 3 3 3 4 5 6 6 7 ...
 # $ : int [1:1000] 0 0 1 2 2 2 3 3 3 4 ...
 # $ : int [1:1000] 1 1 2 3 3 3 3 3 4 4 ...
 # $ : int [1:1000] 0 1 1 2 3 3 4 4 4 5 ...
 # $ : int [1:1000] 0 0 1 2 2 3 3 4 4 5 ...

Upvotes: 2

Related Questions