使用R中的数组进行矩阵切片

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

Matrix Slicing with Array in R

问题

考虑以下的2D数组:

A = 
1 2 3 
4 5 6
7 8 9

给定一组与列对应的索引,例如,i = [0, 2],我想要在R中获得一个仅包含第0列和第2列的新矩阵。

1 3
4 6
7 9

在Python中,我们可以使用以下代码行:A[:, i]。然而,在R中,我不知道如何做到这一点。你能提供一个解决方案吗?

英文:

Consider the following 2D array:

A = 
1 2 3 
4 5 6
7 8 9

Given a set of indexes corresponding to the columns, for instance, i = [0, 2], I want to obtain a new matrix only with the 0th and 2nd column using R.

1 3
4 6
7 9

In Python, we can use the following line: A[:, i]. However, in R, I have no idea to do this. Could you provide me a solution?

答案1

得分: 1

在R中,数据结构中元素的索引从1开始。

A <- matrix(data = 1:9, nrow = 3, byrow = TRUE)

A[,-2]

或者

A[,c(1,3)]
英文:

In R, the index of elements in data structures starts at 1

A &lt;- matrix(data = 1:9,nrow = 3,byrow = TRUE)

A[,-2]

or

A[,c(1,3)]

huangapple
  • 本文由 发表于 2023年6月19日 09:50:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/76503191.html
匿名

发表评论

匿名网友

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

确定