R语言 重复评估一个表达式 – replicate()函数
R语言中的 replicate() 函数被用来重复评估一个函数或表达式。它是R语言基础包中apply系列的成员。在这篇文章中,我们将通过实例来学习replicate()函数的语法和实现。
语法: replicate(n, expr, simplify)
参数:
n: 代表表达式要被评估的次数
expr: 代表表达式
simplify: 代表逻辑值。如果是TRUE,输出以向量或矩阵形式表示,否则以列表形式表示。
例1 :
# Set the seed
set.seed(10)
# Generate random numbers with mean = 0 and sd = 1
x <- rnorm(5, mean = 0, sd = 1)
# Print
print(x)
# Evaluating it repeatedly
r <- replicate(n = 3, rnorm(5, 0, 1), simplify = FALSE )
# Print
print(r)
输出
[1] 0.01874617 -0.18425254 -1.37133055 -0.59916772 0.29454513
[[1]]
[1] 0.3897943 -1.2080762 -0.3636760 -1.6266727 -0.2564784
[[2]]
[1] 1.1017795 0.7557815 -0.2382336 0.9874447 0.7413901
[[3]]
[1] 0.08934727 -0.95494386 -0.19515038 0.92552126 0.48297852
例2 :
# Output to be present as PNG file
png(file = "replicateGFG.png")
# Set the seed
set.seed(10)
# Replicate values and create histogram
hist(replicate(100, mean(rexp(10))))
# Saving the file
dev.off()
输出: