当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 set.seed()用法及代码示例


set.seed()R语言中的函数用于创建可以复制的随机数。它有助于在每次调用随机函数时创建相同的随机数。这有助于为分析创建可重复的数据集。

用法: set.seed(n)

参数:
n:可重复数据集的种子

范例1:


# R program to create repeatable data sets
  
# Setting seeds
set.seed(10)
  
# Creating data set of random values
x <- rnorm(15)
x
  
# Setting seed again for another data set
set.seed(10)
  
# Creating another data set
y <- rnorm(15)
y
  
# Checking if both are equal
identical(x, y)

输出:

 [1]  0.01874617 -0.18425254 -1.37133055 -0.59916772  0.29454513  0.38979430
 [7] -1.20807618 -0.36367602 -1.62667268 -0.25647839  1.10177950  0.75578151
[13] -0.23823356  0.98744470  0.74139013
 [1]  0.01874617 -0.18425254 -1.37133055 -0.59916772  0.29454513  0.38979430
 [7] -1.20807618 -0.36367602 -1.62667268 -0.25647839  1.10177950  0.75578151
[13] -0.23823356  0.98744470  0.74139013
[1] TRUE

范例2:


# R program to create repeatable data sets
  
# Setting seeds
set.seed(10)
  
# Creating data set of random values
x <- rexp(15)
x
  
# Setting seed again for another data set
set.seed(10)
  
# Creating another data set
y <- rexp(15)
y
  
# Checking if both are equal
identical(x, y)

输出:

 [1] 0.01495641 0.92022120 0.75215894 1.57504185 0.23165862 1.08667300
 [7] 2.32762287 0.72912382 1.28831010 0.67226829 0.42652979 1.11542195
[13] 1.31654707 0.41329383 0.67657533
 [1] 0.01495641 0.92022120 0.75215894 1.57504185 0.23165862 1.08667300
 [7] 2.32762287 0.72912382 1.28831010 0.67226829 0.42652979 1.11542195
[13] 1.31654707 0.41329383 0.67657533
[1] TRUE



相关用法


注:本文由纯净天空筛选整理自nidhi_biet大神的英文原创作品 Generate Data sets of same Random Values in R Programming – set.seed() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。