📜  在 R 编程中重复评估表达式 - 复制()函数

📅  最后修改于: 2022-05-13 01:55:19.332000             🧑  作者: Mango

在 R 编程中重复评估表达式 - 复制()函数

R 语言中的replicate()函数用于重复计算函数或表达式。它是 R 基础包中apply家族的成员。在本文中,我们将借助示例学习replicate()函数的语法和实现。

示例 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()

输出: