简体   繁体   English

创建序列基于前一个元素的值

[英]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. 我正在尝试获得20个长度为1000的序列,每个序列通过在序列中的前一个元素中随机添加1或0来生成。

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. 但lapply中的for循环似乎没有做任何事情,我留下了20个1000 0列表的列表。

What is a working way to do this? 这样做的工作方式是什么? If there's a way to do it without a loop, even better :) 如果没有循环可以做到这一点,甚至更好:)

Thanks 谢谢

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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