gpt4 book ai didi

R - 选择满足多个条件的矩阵行的最快方法

转载 作者:行者123 更新时间:2023-12-04 05:39:43 26 4
gpt4 key购买 nike

这是对 returning the rows of a matrix that meet a condition 问题的扩展在 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 == 7matrix$three == 12尽可能快地。这是我知道的方法:
 out <- mat[mat$two == 7,]
final_out <- out[out$three == 12, ]

显然应该有获取 final_out内容的方法在单行中,类似于: final_out <- which(mat$two == 7 && mat$three == 12)这比上面的两行代码更快更简洁。

返回此多条件矩阵查询的最快 R 代码是什么?

最佳答案

只需使用 [用逻辑比较子集...

#  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 - 选择满足多个条件的矩阵行的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18128516/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com