當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。