随机数

基本类型 / 数字 / 整型

# 两端都包含
rand <- sample(0:2, 1)
# rand is 0, 1 or 2

# 单个数字 n 表示 1:n
rand2 <- sample(3, 1)
# rand2 is 1, 2 or 3

# 随机元素
rand3 <- sample(c("red", "green", "blue"), 1)
# rand3 是其中一种颜色

# 陷阱:只剩一个元素时,它会被当作 1:n
candidates <- c(3, 7, 9)
big <- candidates[candidates > 8]
pick <- sample(big, 1)
# pick 在 1 到 9 之间,并不总是 9

cat("rand =", rand, "\n")
cat("rand2 =", rand2, "\n")
cat("rand3 =", rand3, "\n")
cat("pick =", pick, "\n")