优雅的索引直到向量/矩阵的结尾 [英] Elegant indexing up to end of vector/matrix

查看:20
本文介绍了优雅的索引直到向量/矩阵的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 R 中说 - 我想要从位置 i 到向量/矩阵末尾的所有索引?假设我想要一个从第 3 列开始的子矩阵.我目前只知道这种方式:

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:ncol(A)] # get submatrix from 3rd column onwards

但是我真的需要编写 ncol(A) 吗?没有什么优雅的方式怎么说从第 3 列开始"吗?类似 A[,3:] 的东西?(或 A[,3:...])?

But do I really need to write ncol(A)? Isn't there any elegant way how to say "from the 3rd column onwards"? Something like A[,3:]? (or A[,3:...])?

推荐答案

有时告诉 R 你想要什么会更容易.换句话说,使用负索引从矩阵中排除列:

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)]

结果:

     [,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 来查找行数.)


But to answer your question as asked: Use ncol to find the number of columns. (Similarly there is nrow 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆