Skip to content
Related Articles

Related Articles

Improve Article

Create a list with random values in R

  • Last Updated : 02 Sep, 2021

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

R




# 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 : 

  • In the first step, we have created a list using the sample function for generating random values.
  • In the sample function, we have taken vectors with 1 to 10 values as the first parameter.
  • As the second parameter, we have taken size=10. Since we have taken size=10 it will generate 10 random values from the vector
  • As the third parameter, we have taken replace=F. So, no value will be repeated.
  • Finally, printing the list variable.

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.

R




# 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 

R




# 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 :

  • In the fourth parameter, we have taken the prob attribute and assigned some probabilities for the vector values. The first value in the prob represents the probability for the first value of the vector. likewise v1=> p1 , v2 => p2. . . . . . vn => pn . Here v represents vector and p represents prob.
  • In the output, we can observe that 1 is not there. Because we have given probability as 0.02 . Due to less probability, it is not generated by the r interpreter. Other than 1 all the values are generated and repeated since they have a greater probability as compared to 1.



My Personal Notes arrow_drop_up
Recommended Articles
Page :