【问题标题】:keep the returned matrix after indexing as a vector将索引后返回的矩阵保留为向量
【发布时间】:2019-05-27 15:44:51
【问题描述】:

我遵循了一个关于 R 语言的教程 https://www.datamentor.io/r-programming/matrix/,关于如何在索引矩阵而不是向量后保留返回的矩阵。但是,它不起作用,返回矩阵的类仍然是一个向量

我尝试使用一个逗号,然后使用两个逗号,就像教程中显示的那样。

[1] 3 6 9
> class(x[x%%3==0])
[1] "integer"
> x[x%%3==0, drop=FALSE]
[1] 3 6 9
> class(x[x%%3==0, drop=FALSE])
[1] "integer"
> x[x%%3==0,, drop=FALSE]
Error in x[x%%3 == 0, , drop = FALSE] : 
  (subscript) logical subscript too long
> x[x%%3==0,,.drop=FALSE]
Error in x[x%%3 == 0, , .drop = FALSE] : incorrect number of dimensions
> x[x%%3==0,,drop=FALSE]
Error in x[x%%3 == 0, , drop = FALSE] : 
  (subscript) logical subscript too long
> class(x[x%%3==0, drop=FALSE])
[1] "integer"

类仍然是整数,而不是矩阵,这是 drop=FALSE 应该做的

【问题讨论】:

  • 请注意,当您在矩阵/数据/帧上执行x %%3 == 0 时,输出是逻辑矩阵。您将其作为行索引传递
  • 你需要x[rowSums(x%%3==0) == 3, , drop = FALSE]

标签: r matrix vector


【解决方案1】:

的输出
x %% 3==0
#     A     B     C
#X FALSE FALSE FALSE
#Y FALSE FALSE FALSE
#Z  TRUE  TRUE  TRUE

是一个逻辑矩阵

使用逻辑矩阵对初始矩阵进行子集化,根据TRUE的位置给出元素

which(x%%3 == 0)
#[1] 3 6 9

这些与我们从提取中获得的 matrix 中的值相同,这不会区分任何行,例如

x > 3
#     A    B    C
#X FALSE TRUE TRUE
#Y FALSE TRUE TRUE
#Z FALSE TRUE TRUE

x[x > 3]
#[1] 4 5 6 7 8 9

为了这样提取行,我们可能需要获取一个逻辑向量。一种选择是rowSums 并与列数进行比较

x[rowSums(x %%3 == 0) == ncol(x),, drop = FALSE]
#  A B C
#Z 3 6 9

数据

x <- matrix(1:9, nrow = 3, dimnames = list(c("X","Y","Z"), c("A","B","C")))

【讨论】:

  • 但是当矩阵设置为byrow=TRUE时我们应该怎么做呢?当我将矩阵设置为 byrow=TRUE 并且 rowSums、colSums 和 nrow 之间的所有组合时,我尝试过,ncol 不起作用。
  • @user39178 不确定您的意思。
  • 是这样的&gt; x &lt;- matrix(1:9, nrow = 3, byrow=TRUE, dimnames = list(c("X","Y","Z"), c("A","B","C"))) &gt; x[rowSums(x%%3==0)==ncol(x),,drop=FALSE] A B C &gt; x[colSums(x%%3==0)==ncol(x),,drop=FALSE] A B C Z 7 8 9 &gt; x[rowSums(x%%3==0)==nrow(x),,drop=FALSE] A B C &gt; x[colSums(x%%3==0)==nrow(x),,drop=FALSE] A B C Z 7 8 9
  • @user39178 您可以检查x%%3 == 0 的输出,那里只有一列'C'。在那种情况下,我不知道您的子集标准是什么。如果是子集 'C' 列,x[, colSums(x%%3 == 0)== ncol(x), drop = FALSE]
  • 当我这样做时,输出仍然是一行 3 6 9
猜你喜欢
  • 1970-01-01
  • 2014-09-23
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多