使用 runif 和 rnorm 重复创建不同序列的向量

Create a vector of different sequence repeated with runif and rnorm

我想做类似的事情:

vector <-  c(runif(3),rnorm(1), runif(3), rnorm(1)) 

我试过了:

vector <- rep( c(runif(3), rnorm(1) ), times = 2) )

但问题是它是相同序列的两倍

如果你能帮助我,请。

祝你有愉快的一天

您可以先填充声明完整向量,然后一次填充每个分布的索引:

out_length = 4L * 2L
# every fourth element will come from rnorm; the rest from runif
norm_idx = seq(4L, out_length, by = 4L)
n_norm = length(norm_idx)

# declare output
out = numeric(out_length)
out[norm_idx] = rnorm(n_norm)
out[-norm_idx] = runif(out_length - n_norm)

或者,这里有一个使用矩阵索引来完成此操作的棘手方法:

set.seed(394839)
m = matrix(0, nrow = 4L, ncol = 2L)

m[1:3, ] = runif(3L * ncol(m))
m[4L,  ] = rnorm(ncol(m))

c(m)
# [1]  0.4478556  0.1336022  0.5860134 -0.1626707  0.7055598  0.7631879  0.3132743  1.5485366

在 R 中,矩阵只是具有维度的向量,它们逐列填充——因此我们可以声明这个矩阵:

#       [,1] [,2] [,3] [,4] [,5]
# [1,]    1    3    5    7    9
# [2,]    2    4    6    8   10

像这样:

matrix(1:10, nrow = 2L, ncol = 5L)

考虑到这一点,我们可以通过使 3-1 成为每一列中的模式来复制您的 3-1-3-1 模式。

您可以通过放大来确认它是否有效(因此小样本效果被静音):

nrep = 1e4
set.seed(39893)
m = matrix(0, nrow = 4L, ncol = nrep)

m[1:3, ] = runif(3L * nrep)
m[4L,  ] = rnorm(nrep)

out = c(m)

idx = seq(4L, length(out), by = 4L)

plot(density(out[idx]), main = 'Normally distributed')
plot(density(out[-idx]), main = 'Uniformly distributed')

这正是 replicate 的意思。
来自 help('replicate') 页面(我的重点):

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

set.seed(1234)
vector <-  replicate(2, c(runif(3),rnorm(1)))
vector
#          [,1]        [,2]
#[1,] 0.1137034 0.640310605
#[2,] 0.6222994 0.009495756
#[3,] 0.6092747 0.232550506
#[4,] 0.3143686 0.429124689

编辑

经过中的解释,我相信下面的内容更接近问题的要求。请注意,每个 2x2 矩阵都具有正确顺序的先前输出中的元素。

set.seed(1234)
W <- array(dim = c(2, 2, 2))
W[] <- replicate(2, c(runif(3), rnorm(1)))
W
#, , 1
#
#          [,1]      [,2]
#[1,] 0.1137034 0.6092747
#[2,] 0.6222994 0.3143686
#
#, , 2
#
#            [,1]      [,2]
#[1,] 0.640310605 0.2325505
#[2,] 0.009495756 0.4291247