优雅的索引到向量/矩阵的末尾
R 中是否可以说 - 我想要从位置 i 到向量/矩阵末尾的所有索引? 假设我想要一个从第三列开始的子矩阵。我目前只知道这样:
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)
吗?有没有什么优雅的方式来表达“从第三栏开始”?像A[,3:]
之类的东西? (或A[,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
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:...]
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有时,告诉 R 你不想要什么会更容易。换句话说,使用负索引从矩阵中排除列:
以下是两种产生相同结果的替代方法:
结果:
但要按要求回答您的问题:使用
ncol
查找列数。 (类似地,可以使用nrow
来查找行数。)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:
Results:
But to answer your question as asked: Use
ncol
to find the number of columns. (Similarly there isnrow
to find the number of rows.)对于行(不是您的示例中的列),可以使用
head()
和tail()
。几乎相同
(打印的行名/索引都不同)。
这些也适用于向量和数据框:
对于列版本,您可以调整
tail()
,但这有点棘手。我想知道NROW()
和NCOL()
在这里是否有用,而不是dim()
?:或者翻转它的头并与其向 R 索取东西,不如要求它放弃东西。这是一个封装了这个的函数:
For rows (not columns as per your example) then
head()
andtail()
could be utilised.is almost the same as
(the rownames/indices printed are different is all).
Those work for vectors and data frames too:
For the column versions, you could adapt
tail()
, but it is a bit trickier. I wonder ifNROW()
andNCOL()
might be useful here, rather thandim()
?:Or flip this on its head and instead of asking R for things, ask it to drop things instead. Here is a function that encapsulates this:
您可以使用以下指令:
You can use the following instruction:
针对同一件事的 dplyr 可读更新方法:
A dplyr readable renewed approach for the same thing: