Open In App

Select Random Element from List in R

Last Updated : 19 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 1: R program to create a list of numbers and return one  random element

R
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 2: R program to create a list of numbers and return one  random element

We create a numeric vector containing the elements 1 to 5. Then, we define a character string data with the value "Hello Geek." These two objects are combined into a list. The line list1[[sample(1:length(list1), 1)]] uses the sample() function to randomly select an index (either 1 or 2) from the list

R
vec=c(1,2,3,4,5)

data="Hello Geek"

list1=list(vec,data)

list1[[sample(1:length(list1), 1)]]

Output:

Test 1:
[1] 1 2 3 4 5
Test 2:
Hello Geek

Next Article

Similar Reads