Search code examples
rmatrixlabelassign

Create a sequence of random numbers with labels


I want to generate random probability numbers which each of them has a label. For example, by generating 3 numbers, we have three labels:

n <- 3
prob <- runif(n,0,1)
[1] 0.3199110 0.2809717 0.6234215

lab <- LETTERS[1:n]
[1] "A" "B" "C"

assignnn <- data.frame(lab , prob)
lab      prob
1   A 0.3199110
2   B 0.2809717
3   C 0.6234215

If i sample from these three numbers and use them in a matrix:

sam <- sample(prob , 6 , replace = TRUE)
[1] 0.2809717 0.3199110 0.2809717 0.3199110 0.2809717 0.6234215

mat <- matrix(sam,2,3)
          [,1]      [,2]      [,3]
[1,] 0.2809717 0.2809717 0.2809717
[2,] 0.3199110 0.3199110 0.6234215

I want to get the label matrix as below:

       [,1]      [,2]      [,3]
[1,]    B         B          B
[2,]    A         A          C

Solution

  • Is this what you are looking for?

    # Set n = 3
    n <- 3
    
    # Take a random sample from a uniform distribution
    prob <- runif(n, 0, 1)
    
    # Assign names to the elements of 'prob'
    names(prob) <- LETTERS[1:n]
    
    # View prob
    prob
    #>         A         B         C 
    #> 0.1631039 0.6475393 0.5345181
    
    # Take a random sample of n = 6 from 'prob' (with replacement)
    sam <- sample(prob, 6, replace = TRUE)
    
    # View 'sam'
    sam
    #>         A         C         A         B         A         A 
    #> 0.1631039 0.5345181 0.1631039 0.6475393 0.1631039 0.1631039
    
    # Create a matrix
    matrix(sam, 2, 3)
    #>           [,1]      [,2]      [,3]
    #> [1,] 0.1631039 0.1631039 0.1631039
    #> [2,] 0.5345181 0.6475393 0.1631039
    
    # Matrix using the element names
    matrix(names(sam), 2, 3)
    #>      [,1] [,2] [,3]
    #> [1,] "A"  "A"  "A" 
    #> [2,] "C"  "B"  "A"
    

    Created on 2020-06-27 by the reprex package (v0.3.0)