R - 从矩阵中提取满足给定条件的行?

发布于 2024-11-19 05:57:02 字数 334 浏览 3 评论 0原文

       [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    1
[3,]    0    1    0
[4,]    0    0    1
[5,]    1    0    0

给定一个像上面这样的矩阵 - 迭代矩阵的有效方法是什么,选择第一个元素为 1 且所有其他元素为 0 的行,以便

       [,1] [,2] [,3]    
[1,]    1    0    0    
[2,]    1    0    0

返回?

谢谢, D .

       [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    1
[3,]    0    1    0
[4,]    0    0    1
[5,]    1    0    0

Given a matrix like that above - what is an efficient way to iterate over the matrix, selecting rows for which the first element is 1 and all other elements are 0, such that

       [,1] [,2] [,3]    
[1,]    1    0    0    
[2,]    1    0    0

is returned?

Thanks,
D.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦亦如幻 2024-11-26 05:57:02

重新创建数据:

a <- array(c(1,0,0,0,1,0,1,1,0,0,0,1,0,1,0), dim=c(5,3))

现在创建一个等于条件的向量。

cond <- c(1, 0, 0)

接下来,包装在对 which 的调用中的 apply 语句将告诉您哪些行符合您的条件

which(apply(a, 1, function(x)all(x==cond)))
1] 1 5

最后,提取满足此条件的行:

x <- which(apply(a, 1, function(x)all(x==cond)))
a[x, ]


     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    1    0    0

生成的数组不'包含很多信息。也许您想知道有多少行符合条件?

length(x)
[1] 2

来回答下一个问题。当数组很大时如何创建条件向量?

嗯,一种方法如下。假设您有一个 100 列宽的数组,因此您需要一个长度为 100 的向量,并且您希望第三个元素为 1:

cond <- rep(0, 100)
cond[3] <- 1
cond
  [1] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Recreate the data:

a <- array(c(1,0,0,0,1,0,1,1,0,0,0,1,0,1,0), dim=c(5,3))

Now create a vector that equals the condition.

cond <- c(1, 0, 0)

Next, an apply statement wrapped in a call to which will tell you which rows match your condition

which(apply(a, 1, function(x)all(x==cond)))
1] 1 5

Finally, to extract the rows where this condition is met:

x <- which(apply(a, 1, function(x)all(x==cond)))
a[x, ]


     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    1    0    0

The resulting array doesn't contain much information. Perhaps you wanted to know how many rows match the condition?

length(x)
[1] 2

To answer the follow-on question. How to create a condition vector when the array is large?

Well, one way is as follows. Let's say you have an array of 100 columns wide, so you need a vector of 100 in length, and you want the third element to be a 1:

cond <- rep(0, 100)
cond[3] <- 1
cond
  [1] 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文