R语言 从数据集中生成一组样本数据 – sample()函数

R语言 从数据集中生成一组样本数据 – sample()函数

R语言中的 sample() 函数根据函数调用中提供的参数创建随机样本。它把一个矢量或一个正整数作为函数参数中的对象。

语法:

sample(x, size, replace)

参数:

x: 表示矢量或正整数或数据框

size: 表示要抽取的样本的大小

replace: 表示逻辑值。如果为 “true”,样本可能有多个相同的值。

要了解更多的可选参数,请在控制台使用以下命令。

help("sample")
R

例1 :

# Create sample
x <- sample(1:100, 10, replace=TRUE)
  
# Print
# Output may differ each time the command is executed
print(x)
R

输出。

[1] 47 52 22 98 75 94 91 94 42 53
R

例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, ])
R

输出。

                  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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程