I am porting part of a program (not enough to compile and run) from R to C++. I am not familiar with R. I have done okay using the references online, but was stumped by the following line:
cnt2.2<-cnt2[,-1]
I am guessing:
cnt2
is a 2 dimensional matrixcnt2.2
is a new variable being declared with a period '.' used the same way an alphabetic character would be.<-
is an assignment.[,-1]
accesses part of the array. I thought [,5]
meant all rows, 5th column only. If this is correct, I have no idea what -1 refers to.Negative indices are powers (also called exponents) with a minus sign in front of them. E.g. We get negative indices by dividing two terms with the same base where the first term is raised to a power that is smaller than the power that the second term is raised to.
In the R programming language, you can use a negative index in order to exclude an element from a list or a row from a matrix.
Using a negative number as an index in the slice method is called Negative slicing in Python. It returns the nth element from the right-hand side of the list (as opposed to the usual left-hand side).
An important aspect of working with R objects is knowing how to “index” them Indexing means selecting a subset of the elements in order to use them in further analysis or possibly change them Here we focus just on three kinds of vector indexing: positional, named reference, and logical Any of these indexing techniques ...
This is covered in section 2.7 of the manual: http://cran.r-project.org/doc/manuals/R-intro.html#Index-vectors
It is a negative index into the cnt2
object specifying all rows and all columns except the first column.
Negative indices specify dropping (rather than retaining) particular elements ... so x[,-1]
specifies dropping the first column (rows are the first dimension, before the comma, and columns are the second dimension, after the comma). From ?"["
( http://stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.html ):
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
1) cnt2 is a 2 dimensional matrix
From the code you provided it is indeed a 2-dimensional structure of some sort (quite possibly a matrix).
2) cnt2.2 is a new variable being declared with a period '.' used the same way an alphabetic character would be.
Correct.
3) <- is an assignment.
Correct.
4) [,-1] accesses part of the array. I thought [,5] meant all rows, 5th column only. If this is correct, I have no idea what -1 refers to.
[,-1]
selects all columns except column 1. Note that, unlike in C++, indices in R start from one rather than zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With