R-选择满足多个条件的矩阵行的最快方法 [英] R - fastest way to select the rows of a matrix that satisfy multiple conditions
本文介绍了R-选择满足多个条件的矩阵行的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是对返回R中满足条件的矩阵行.说我有矩阵:
one two three four
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 11 18
[4,] 4 9 11 19
[5,] 5 10 15 20
[6,] 1 6 15 20
[7,] 5 7 12 20
我想返回所有行,其中matrix$two == 7
和matrix$three == 12
尽可能快.这是我知道的方法:
I want to return all rows, where matrix$two == 7
AND matrix$three == 12
as fast as possible. This is the way I know to do it:
out <- mat[mat$two == 7,]
final_out <- out[out$three == 12, ]
显然应该有一种方法可以单行获取final_out
的内容,例如:final_out <- which(mat$two == 7 && mat$three == 12)
,它比上面的两行代码更快,更简洁.
There should obviously be a method to get the contents of final_out
in a one-liner, something like: final_out <- which(mat$two == 7 && mat$three == 12)
that is faster and more succinct than the two line of codes above.
返回此多条件矩阵查询最快的R代码是什么?
What is the fastest R code to return this multiple condition matrix query?
推荐答案
只需在逻辑比较中使用[
子设置...
Just use [
subsetting with logical comparison...
# Reproducible data
set.seed(1)
m <- matrix( sample(12,28,repl=T) , 7 , 4 )
[,1] [,2] [,3] [,4]
[1,] 4 8 10 3
[2,] 5 8 6 8
[3,] 7 1 9 2
[4,] 11 3 12 4
[5,] 3 3 5 5
[6,] 11 9 10 1
[7,] 12 5 12 5
# Subset according to condition
m[ m[,2] == 3 & m[,3] == 12 , ]
[1] 11 3 12 4
这篇关于R-选择满足多个条件的矩阵行的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文