ifelse函数而不是for循环
我的原始R代码如下ifelse函数而不是for循环,r,for-loop,if-statement,R,For Loop,If Statement,我的原始R代码如下 Bernoulli <- rbinom(1000, 1, 0.5) mix.sample <- rep(0, 1000) #reserve storage for (i in 1:1000) { #for each Bernoulli realization if (Bernoulli[i] == 1){ #sample corresponding normal component mix.sample[i] <- rnorm(1,
Bernoulli <- rbinom(1000, 1, 0.5)
mix.sample <- rep(0, 1000) #reserve storage
for (i in 1:1000) { #for each Bernoulli realization
if (Bernoulli[i] == 1){ #sample corresponding normal component
mix.sample[i] <- rnorm(1, mean=10, sd=1)
}
else {
mix.sample[i] <- rnorm(1, mean=0, sd=1)
}
}
plot(density(mix.sample))
Bernoulli而不是您可以执行的for
循环
set.seed(42)
sim.fun <- function(x) {
if (x == 1) {
rnorm(1, 10, 1)
} else {
rnorm(1, 0, 1)
}
}
P <- sapply(Bernoulli, sim.fun)
plot(density(P))
不过功能更快
microbenchmark()
产生:
单位:毫秒
expr最小lq平均uq最大neval cld
对于回路8.015976 8.232972 8.712522 8.316147 8.475865 14.65216 100 c
sim.fun 3.622982 3.672990 4.493131 3.700290 3.752339 54.14139 100 a
sapply 5.932761 6.016319 6.479058 6.070026.115951 12.38065 100 b
正如您一次创建整个测试向量(rbinom
),您可以一次创建两个rnorm
向量的所有值。将所有内容放入矩阵中,使用测试向量的值选择两个值列中的任意一个
set.seed(1)
n <- 8
m <- cbind(test = rbinom(n, 1, 0.5),
norm0 = rnorm(n, mean = 0, sd = 1),
norm10 = rnorm(n, mean = 10, sd = 1))
m <- cbind(m, res = m[cbind(1:nrow(m), (m[ , "test"] == 1) + 2)])
# test norm0 norm10 res
# [1,] 0 0.3295078 9.378759 0.3295078
# [2,] 0 -0.8204684 7.785300 -0.8204684
# [3,] 1 0.4874291 11.124931 11.1249309
# [4,] 1 0.7383247 9.955066 9.9550664
# [5,] 0 0.5757814 9.983810 0.5757814
# [6,] 1 -0.3053884 10.943836 10.9438362
# [7,] 1 1.5117812 10.821221 10.8212212
# [8,] 1 0.3898432 10.593901 10.5939013
# [10,] 0 1.1249309 10.619826 1.1249309
set.seed(1)
n就个人而言,我会使用这样一个事实,即您可以立即将二项式
转换为逻辑
Bernoulli <- as.logical(rbinom(1e3, 1, 0.5))
samp <- numeric(1e3)
n <- sum(Bernoulli)
samp[Bernoulli] <- rnorm(n, 10, 1)
samp[!Bernoulli] <- rnorm(1e3 - n)
samp
Bernoulli另一个选项是将值放入数据帧中,然后使用ifelse添加变量,就像您在开始时尝试的那样。这里我也只是绘制数据,但您可以将其分配回存储值
library(tidyverse)
set.seed(81)
df <- data_frame(Bernoulli = rbinom(1000, 1, 0.5))
df %>%
mutate(mix.sample = if_else(Bernoulli == 1,
rnorm(1, mean=10, sd=1),
rnorm(1, mean=0, sd=1))) %>%
ggplot(aes(mix.sample))+
geom_density()+
scale_x_continuous(limits = c(-5, 15))
库(tidyverse)
种子(81)
df%
变异(mix.sample=if_else)(伯努利=1,
rnorm(1,平均值=10,标准差=1),
rnorm(1,平均值=0,标准差=1))%>%
ggplot(aes(混合样品))+
几何密度()+
标度x连续(限值=c(-5,15))
Bernoulli <- as.logical(rbinom(1e3, 1, 0.5))
samp <- numeric(1e3)
n <- sum(Bernoulli)
samp[Bernoulli] <- rnorm(n, 10, 1)
samp[!Bernoulli] <- rnorm(1e3 - n)
samp
library(tidyverse)
set.seed(81)
df <- data_frame(Bernoulli = rbinom(1000, 1, 0.5))
df %>%
mutate(mix.sample = if_else(Bernoulli == 1,
rnorm(1, mean=10, sd=1),
rnorm(1, mean=0, sd=1))) %>%
ggplot(aes(mix.sample))+
geom_density()+
scale_x_continuous(limits = c(-5, 15))