I randomly sample values from the first row of matrix A:
#1 2 3 4 5 6 7 8 9
A <- matrix(data=c( 0, 0, 0.33, 0.37, 0, 0, 0, 0.3, 0, #1
0, 0, 0, 0, 0.1, 0, 0, 0.9, 0, #2
0.2, 0, 0.1, 0, 0.4, 0, 0, 0.3, 0, #3
0.5, 0, 0,0, 0, 0, 0, 0, 0.5, #4
0, 0.4, 0,0, 0, 0.5, 0, 0, 0.1, #5
0, 0, 0,0, 1, 0, 0, 0, 0, #6
0, 0.2, 0, 0.8, 0, 0, 0, 0,0, #7
1, 0, 0, 0, 0, 0, 0, 0,0, #8
0.1, 0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.1 ),#9
nrow=9, ncol=9)
colnames(A) <- c(1:9)
rownames(A) <- c(1:9)
x <- sample(x=A[,1], size=2, prob=A[,1])
The result is a numeric object that looks, for example, like this:
> x
3 8
0.33 0.30
The 3 and 8 represent important information that I need to store and use for downstream calculations. I have no idea how to extract them - these row numbers seem to be stored as metadata when I View(x):
How can I reshape the results of sample() so that the numeric object that gets output is a vector containing the row numbers (i.e., in this example, I want x to equal c(3, 8))?
CodePudding user response:
How about:
A <- matrix(data=c( 0, 0, 0.33, 0.37, 0, 0, 0, 0.3, 0, #1
0, 0, 0, 0, 0.1, 0, 0, 0.9, 0, #2
0.2, 0, 0.1, 0, 0.4, 0, 0, 0.3, 0, #3
0.5, 0, 0,0, 0, 0, 0, 0, 0.5, #4
0, 0.4, 0,0, 0, 0.5, 0, 0, 0.1, #5
0, 0, 0,0, 1, 0, 0, 0, 0, #6
0, 0.2, 0, 0.8, 0, 0, 0, 0,0, #7
1, 0, 0, 0, 0, 0, 0, 0,0, #8
0.1, 0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.1 ),#9
nrow=9, ncol=9)
colnames(A) <- c(1:9)
rownames(A) <- c(1:9)
x <- names(sample(x=A[,1], size=2, prob=A[,1]))
x
#> [1] "3" "8"
Created on 2022-02-01 by the reprex package (v2.0.1)

