问题
Suppose I have a matrix of values, and a vector which tells me, for each row of the matrix, which (one!) column I'd like to access. How, without a loop, do I retrieve those values?
Data:
dta <- structure(c(0.02, 0.01, 0, 0.08, 0.18, 0.01, 0.12, 0, 0.03, 0,
0.95, 0.96, 0.94, 0.97, 0.98, 0.95, 0.99, 0.91, 0.96, 0.98,
0.98, 0.99, 1, 0.92, 0.82, 0.99, 0.88, 1, 0.97, 1,
0.05, 0.04, 0.06, 0.03, 0.02, 0.05, 0.01, 0.09, 0.04, 0.02),
.Dim = c(20L, 2L), .Dimnames = list(NULL, c("1", "2")))
Vector of indices:
idx <- c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)
Desired output:
0.98
0.98
0.99
0.91
0.82
0.99
0.88
0.99
0.96
0.99
0.95
0.96
0.94
0.96
0.97
0.94
0.98
0.91
0.96
0.97
Background: e1071::cmeans
returns membership
, the membership values of all points to all clusters, and cluster
, the most probable cluster. I would like a vector of the membership values of the most probable clusters to generate transparent colors for a cluster plot.
回答1:
How about
dta <- structure(c(0.02, 0.01, 0, 0.08, 0.18, 0.01, 0.12, 0, 0.03, 0,
0.95, 0.96, 0.94, 0.97, 0.98, 0.95, 0.99, 0.91, 0.96, 0.98,
0.98, 0.99, 1, 0.92, 0.82, 0.99, 0.88, 1, 0.97, 1,
0.05, 0.04, 0.06, 0.03, 0.02, 0.05, 0.01, 0.09, 0.04, 0.02),
.Dim = c(20L, 2L), .Dimnames = list(NULL, c("1", "2")))
idx <- c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)
dta[cbind(1:nrow(dta), idx)]
I clearly assume that length(idx) == nrow(dta)
. If they are not equal, R will stack idx as many times as necessary to have the same amount of elements as we have rows. So if you leave out the last element of idx
you get
idx <- c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L)
dta[cbind(1:nrow(dta), idx)]
[1] 0.98 0.99 1.00 0.92 0.82 0.99 0.88 1.00 0.97 1.00 0.95 0.96 0.94 0.97 0.98 0.95 0.99 0.91 0.96 0.02
where the last element is picked from column two instead of one since R started at idx[1]
again.
回答2:
Or alternatively:
c(dta[which(idx==2),2], dta[which(idx==1),1])
# [1] 0.98 0.99 1.00 0.92 0.82 0.99 0.88 1.00 0.97
# 1.00 0.95 0.96 0.94 0.97 0.98 0.95 0.99 0.91 0.96 0.98
来源:https://stackoverflow.com/questions/37921589/subsetting-a-matrix-using-a-vector-of-indices