Search notes:

R function: sample

Select n random items from a vector.
Without replacement: The same element won't be selected more than once.
With replacement: The same element can be selected more than once.
set.seed(280870)


# Generate a random permutation of a vector:
sample(1:10)
# [1]  4  2  1  6 10  7  8  5  3  9

# get five «random» elements:
sample(1:10, 5)
# [1]  9  3  7  4 10

# Sample normally returns an element at most once. This can
# be changed with the replace argument.
#
# Generate 100 zeroes or ones:
sample(c(0,1), 100, replace = TRUE)
#  [1] 1 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 0 0 0 0 1 1 0 0 0 1 0 0 1 0 1 0 0 0 0 1 1
# [38] 1 1 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 0 0 1 0 1 1 1 0 0 1 0 0 1 0 1 1 1 1 1
# [75] 1 0 1 0 0 0 1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0 1 1 0 0

cat ("\n\n")

# Make zeroes much more probable:
sample(c(0,1), 100, replace = TRUE, prob=c(0.9, 0.1))
#  [1] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 1
# [38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
# [75] 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Github repository about-r, path: /functions/sample.R

See also

Index to (some) R functions

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758200739, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/R/functions/sample(74): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78