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