Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

r - Elegant indexing up to end of vector/matrix

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:...])?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...