sample()
R語言中的函數根據函數調用中提供的參數創建隨機樣本。它接受一個向量或一個正整數作為函數參數中的對象。
用法:
sample(x, size, replace)
參數:
x:表示向量或正整數或 DataFrame
size:表示要采集的樣本大小
replace:表示邏輯值。如果為 TRUE,樣本可能有多個相同的值
要了解更多可選參數,請在控製台中使用以下命令:
help("sample")
範例1:
# Create sample
x <- sample(1:100, 10, replace=TRUE)
# Print
# Output may differ each time the command is executed
print(x)
輸出:
[1] 47 52 22 98 75 94 91 94 42 53
範例2:
# Create sample
pos <- sample(1:nrow(mtcars), 5, replace = TRUE)
# Print sample observations
# Output may differ each time the command is executed
print(mtcars[pos, ])
輸出:
mpg cyl disp hp drat wt qsec vs am gear carb Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2 Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2 Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Hornet 4 Drive.1 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1 Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
相關用法
- R語言 set.seed()用法及代碼示例
- R語言 combn()用法及代碼示例
- R語言 gl()用法及代碼示例
- R語言 rainbow()用法及代碼示例
- R語言 seq_len()用法及代碼示例
- R語言 seq_along()用法及代碼示例
- R語言 data.matrix()用法及代碼示例
- R語言 with()用法及代碼示例
- R語言 is.primitive()用法及代碼示例
- R語言 arrange()用法及代碼示例
- R語言 quantile()用法及代碼示例
- R語言 head()用法及代碼示例
- R語言 tail()用法及代碼示例
- R語言 glm()用法及代碼示例
- R語言 all_equal()用法及代碼示例
- R語言 type.convert()用法及代碼示例
- R語言 is.character()用法及代碼示例
注:本文由純淨天空篩選整理自utkarsh_kumar大神的英文原創作品 Generate a set of Sample data from a Data set in R Programming – sample() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。