Select Random Element from List in R

• Last Updated : 23 Sep, 2021

In this article, we will discuss how to select a random element from a List using R programming language.

We can select a Random element from a list by using the sample() function. sample() function is used to get the random element from the data structure

Syntax:

sample(1:length(list), n)

where

• 1:length(list) is used to iterate all elements over a list
• n represents the number of random elements to be returned

Note: In our case n=1 because we have to get only one random element.

Example: R program to create a list of numbers and return one  random element

R

 `# create a list of integers``list1=``list``(1:10,23,45,67,8)`` ` `# get the random element from the list``list1[[``sample``(1:``length``(list1), 1)]]`

Output:

Test 1:

`[1] 67`

Test 2:

`[1] 45`

Example: R program to create a list of numbers and return one  random element

R

 `# create a vector of integers``vec=``c``(1,2,3,4,5)`` ` `# create a variable``data=``"Hello Geek"`` ` `# pass the vector and variable to list``list1=``list``(vec,data)`` ` `# get the random element from the list``list1[[``sample``(1:``length``(list1), 1)]]`

Output:

`[1] 1 2 3 4 5`
My Personal Notes arrow_drop_up