向量/矩阵结尾的优雅索引 [英] Elegant indexing up to end of vector/matrix
问题描述
R是否可以说 - 我希望位置 i
中的所有索引到向量/矩阵的结尾?
说我想要从第3列开始的子矩阵。我现在只知道这个方式:
A = matrix(rep(1:8,each = 5),nrow = 5) #只需生成一些示例矩阵...
pre>
A [,3:dim(A)[2]]#从第3列开始获取子矩阵
但是我真的需要写这个丑陋的
dim(A)[2]
?没有什么优雅的方式怎么说从第3列开始?像A [,3:]
? (或A [,3:...]
)?解决方案有时候,告诉R你不要 想要什么更容易。换句话说,使用负数索引从矩阵中排除列:
以下是两种产生相同结果的两种替代方法:
A [, - (1:2)]
pre>
A [,-seq_len(2)]
结果:
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3 4 5 6 7 8
[2,] 3 4 5 6 7 8
[3 ,] 3 4 5 6 7 8
[4,] 3 4 5 6 7 8
[5,] 3 4 5 6 7 8
但要回答您的问题:使用
ncol
找到列数。 (同样地,有nrow
来查找行数。)A [,3:ncol(A)]
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 3 4 5 6 7 8
[2,] 3 4 5 6 7 8
[3,] 3 4 5 6 7 8
[4,] 3 4 5 6 7 8
[5,] 3 4 5 6 7 8
Is it possible in R to say - I want all indices from position
i
to the end of vector/matrix? Say I want a submatrix from 3rd column onwards. I currently only know this way:A = matrix(rep(1:8, each = 5), nrow = 5) # just generate some example matrix... A[,3:dim(A)[2]] # get submatrix from 3rd column onwards
But do I really need to write that ugly
dim(A)[2]
? Isn't there any elegant way how to say "from the 3rd column onwards"? Something likeA[,3:]
? (orA[,3:...]
)?解决方案Sometimes it's easier to tell R what you don't want. In other words, exclude columns from the matrix using negative indexing:
Here are two alternative ways that both produce the same results:
A[, -(1:2)] A[, -seq_len(2)]
Results:
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8
But to answer your question as asked: Use
ncol
to find the number of columns. (Similarly there isnrow
to find the number of rows.)A[, 3:ncol(A)] [,1] [,2] [,3] [,4] [,5] [,6] [1,] 3 4 5 6 7 8 [2,] 3 4 5 6 7 8 [3,] 3 4 5 6 7 8 [4,] 3 4 5 6 7 8 [5,] 3 4 5 6 7 8
这篇关于向量/矩阵结尾的优雅索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!