创建带有标签的随机数序列

Create a sequence of random numbers with labels

我想生成随机概率数,每个概率数都有一个标签。例如,通过生成3个数字,我们有三个标签:

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

如果我从这三个数字中抽样并在矩阵中使用它们:

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

我想得到标签矩阵如下:

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

您可以使用 match :

mat[] <- assignnn$lab[match(mat, assignnn$prob)]
mat
#     [,1] [,2] [,3]
#[1,] "C"  "A"  "A" 
#[2,] "C"  "B"  "C" 

数据

set.seed(1235)
n <- 3
prob <- runif(n,0,1)
lab <- LETTERS[1:n]
assignnn <- data.frame(lab , prob)
assignnn
#  lab       prob
#1   A 0.24259237
#2   B 0.51535594
#3   C 0.09942167
sam <- sample(prob , 6 , replace = TRUE)
mat <- matrix(sam,2,3)
mat
#           [,1]      [,2]       [,3]
#[1,] 0.09942167 0.2425924 0.24259237
#[2,] 0.09942167 0.5153559 0.09942167

这是您要找的吗?

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

reprex package (v0.3.0)

于 2020-06-27 创建