用列名表达式来对矩阵进行子集操作。

huangapple go评论70阅读模式
英文:

subset a matrix by a expression with a column name

问题

如何在列名(b)必须在表达式中的情况下,实现以下矩阵的操作?
subset(data, b > 5)

将矩阵转换为数据框可以解决这个问题。但我正在寻找一个专门针对矩阵的解决方案。

英文:

data<- matrix(c(1,2,3,4,5,6,7,8,9), nrow=3)

colnames(data) <- c("a", "b", "c")

How can we achieve the following for a matrix when the columnname (b) must be in the expression?
subset(data, b > 5)

Converting the matrix into a data.frame would work. But I am looking for a solution specifically for a matrix.

答案1

得分: 2

不能在具有名称的矩阵上使用subset,因为列不以单独的对象存储。矩阵实际上只是一个带有额外维度属性的向量。您需要更明确的索引。这将起作用

data[data[,"b"] > 5,]

如果您查看subset.matrix函数,您会发现它只是[,]索引操作的包装器。如果您需要符号b起作用,您需要额外的工作来对数据进行子集操作,这基本上与将数据转换为数据框的工作相同。

英文:

You cannot use subset with a matrix with names because columns are not stored as separate objects. A matrix is all just one vector with an extra dimension attribute. You would need to more explicit indexing. This will work

data[data[,"b"]>5,]

If you look at the subset.matrix function you can see it's just a wrapper to the [,] indexing operation. If you need the symbol b to work, you'd need to do the extra work to subset the data which is basically doing the same work as converting the data to a data.frame.

答案2

得分: 0

你是指这个吗?

> data[data[, deparse(quote(b))] > 5, , drop = FALSE]
     a b c
[1,] 3 6 9

还是这个?

> subset.matrix(data, data[, deparse(quote(b))] > 5)
     a b c
[1,] 3 6 9

注意:

我会说,可以按照你的要求来做,但对于矩阵 data 来说,这不会像 data[data[,"b"]>5,] 那样简单。

英文:

Do you mean this?

> data[data[, deparse(quote(b))] > 5, , drop = FALSE]
     a b c
[1,] 3 6 9

or

> subset.matrix(data, data[, deparse(quote(b))] > 5)
     a b c
[1,] 3 6 9

Note:

I would say, it is POSSIBLE to make it as what you asked for, but it would not be as simple as data[data[,"b"]>5,] for matrix data.

huangapple
  • 本文由 发表于 2023年6月8日 04:05:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76426774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定