R中的随机向量
在本文中,我们将了解如何在 R 编程语言中随机化向量。
Randomize 意味着从向量中获取随机元素,我们可以使用 sample()函数获取向量中的随机元素。
Syntax: sample(data, size, replace)
Parameters:
- data: 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
示例 1: R 语言中的随机化向量。
R
# consider the vector1 with 5 elements
vector1 = c(12, "sravan", "bobby", 56, 78)
random_data = sample(vector1)
# display random data
print(random_data)
R
# consider the vector1 with 30 elements
vector1 = c(12,1,2,3,4,5,
"sravan","bobby",
56,78,1:20)
random_data = sample(vector1)
# display random data
print("random data: ")
print(random_data)
# get the random vector from
# the above vector with 10 elements
print("random data with 10 element : ")
random_data = sample(vector1,10)
# display random data
print(random_data)
输出:
[1] "sravan" "78" "12" "bobby" "56"
例 2: R 程序获取随机向量并显示。
电阻
# consider the vector1 with 30 elements
vector1 = c(12,1,2,3,4,5,
"sravan","bobby",
56,78,1:20)
random_data = sample(vector1)
# display random data
print("random data: ")
print(random_data)
# get the random vector from
# the above vector with 10 elements
print("random data with 10 element : ")
random_data = sample(vector1,10)
# display random data
print(random_data)
输出:
[1] “random data: “
[1] “2” “7” “3” “1” “5” “bobby” “4” “11”
[9] “6” “8” “13” “14” “56” “15” “17” “20”
[17] “19” “12” “5” “78” “3” “1” “12” “18”
[25] “16” “4” “9” “sravan” “2” “10”
[1] “random data with 10 element : “
[1] “11” “20” “78” “16” “bobby” “14” “1” “17”
[9] “sravan” “4”