Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 只有两个数字的随机数列表_R_Random - Fatal编程技术网

R 只有两个数字的随机数列表

R 只有两个数字的随机数列表,r,random,R,Random,这真的很简单,但我总是被卡住!我试图在R中创建一个1000个零的列表,数字1.5以随机间隔添加20次,如下所示: 0.000 0.000 1.500 0.000 1.500 0.000 0.000 但我一直在思考如何将它保持为两个数字?我一直在使用seq命令,但无法正确获取参数…对索引进行采样: x <- numeric(1000) #adjust to 1020 if you really need 1000 zeros in the result x[sample(length(x)

这真的很简单,但我总是被卡住!我试图在R中创建一个1000个零的列表,数字1.5以随机间隔添加20次,如下所示:

0.000
0.000
1.500
0.000
1.500
0.000
0.000
但我一直在思考如何将它保持为两个数字?我一直在使用seq命令,但无法正确获取参数…

对索引进行采样:

x <- numeric(1000) #adjust to 1020 if you really need 1000 zeros in the result
x[sample(length(x), 20)] <- 1.5
x怎么样

x <- rep(0, 1000)
positions <- round(runif(20, 1, 1000))
x[positions] <- 1.5
x

在我上面的解决方案中,当你说“添加”时,我假设你的意思是“插入”,因此给出了一个长度为1020的向量。如果您的意思是“添加”(与零相反的添加),您可以使用:

sample(c(double(980L),rep(1.5,20L)));

这可能会导致少于20个赋值,基本上是用替换进行采样。嗯,我认为OP的意思是“插入”而不是“添加”,即1000个零,20个1.5s以随机间隔插入,总长度为1020。您想要的输出不清楚。最后总共有多少个零?1000或980?另一种选择是先创建你想要的
rep(c(0,1.5),c(980,20))
,然后随机排列
rep(c(0,1.5),c(980,20))[样本(1000)]
sample(c(double(980L),rep(1.5,20L)));