Generate a set of Sample data from a Data set in R Programming – sample() Function

sample() function in R Language creates random sample based on the parameters provided in the function call. It takes either a vector or a positive integer as the object in the function parameter.

Syntax:
sample(x, size, replace)

Parameters:
x: indicates either vector or a positive integer or data frame
size: indicates size of sample to be taken
replace: indicates logical value. If TRUE, sample may have more than one same value

To know about more optional parameters, use below command in console:

help("sample")

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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, ])

chevron_right


Output:

                  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
My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.