Open In App

Create a list with random values in R

In this article, we are going to see how to create a list with random values in R programming language.

The list can store data of multiple data type. A List can store multiple R objects like different types of atomic vectors such as character, numeric, logical. We can create a list using list() function. We need to pass vector(s) as parameters.



Syntax : list_variable = list( vector 1,vector 2, . . . . , vector n )

We can generate random values using the sample function:



Syntax : sample( vector , size=value , replace=T or F , prob=c(probability values for the vector) )

Note : Here prob is not mandatory to pass . prob refers the probability of values to be repeated .

Example 1: With replace as FALSE




# creating a list with sample function
lst1 = list(sample(1 : 10, size = 10, replace = F))
 
# printing the list variable
print(lst1)

Output :

[[1]]
 [1]  7  4  9  1  2  3 10  6  8  5

Explanation : 

Example 2: With replace as TRUE

The main point here to remember is if we want to assign replace=FALSE, size is always less than or equal to vector size, otherwise, execution will be halted.




# creating a list with sample function
lst1 = list(sample(1 : 10, size = 15, replace = T))
 
# printing the list variable
print(lst1)

Output :

[[1]]
 [1]  1  7  8  7 10  2  3  7  8  1  9  7  9  1  1

Example 3: With prob attribute 




# creating a list with sample function
lst1 = list(sample(1 : 5, size = 15,
                   replace = T,
                   prob = c(0.02, 0.2, 0.25, 0.5, 0.9)))
 
# printing the list variable
print(lst1)

Output :

[[1]]
 [1] 3 3 5 5 5 4 4 4 3 5 4 4 3 2 5

Code explanation :


Article Tags :