returning matrix column indices matching value(s) in R -
i'm looking fast way return indices of columns of matrix match values provided in vector (ideally of length 1 or same number of rows in matrix) instance:
mat <- matrix(1:100,10) values <- c(11,2,23,12,35,6,97,3,9,10)
the desired function, call rowmatches()
return:
rowmatches(mat, values) [1] 2 1 3 na 4 1 10 na 1 1
indeed, value 11 first found @ 2nd column of first row, value 2 appears @ 1st column of 2nd row, value 23 @ 3rd column of 3rd row, value 12 not in 4th row... , on.
since haven't found solution in package matrixstats, came function:
rowmatches <- function(mat,values) { res <- integer(nrow(mat)) matches <- mat == values (col in ncol(mat):1) { res[matches[,col]] <- col } res[res==0] <- na res }
for intended use, there millions of rows , few columns. splitting matrix rows (in list called, say, rows
) , calling map(match, as.list(values), rows)
way slow.
i'm not satisfied function because there loop, may slow if there many columns. should possible use apply()
on columns, won't make faster.
any ideas?
res <- arrayind(match(values, mat), .dim = dim(mat)) res[res[, 1] != seq_len(nrow(res)), 2] <- na # [,1] [,2] # [1,] 1 2 # [2,] 2 1 # [3,] 3 3 # [4,] 2 na # [5,] 5 4 # [6,] 6 1 # [7,] 7 10 # [8,] 3 na # [9,] 9 1 #[10,] 10 1
Comments
Post a Comment