19

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:

  1. cnt2 is a 2 dimensional matrix
  2. cnt2.2 is a new variable being declared with a period '.' used the same way an alphabetic character would be.
  3. <- is an assignment.
  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.
Ricardo Oliveros-Ramos
  • 4,322
  • 2
  • 25
  • 42
Brad
  • 1,360
  • 4
  • 18
  • 27

3 Answers3

27

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.

Chase
  • 67,710
  • 18
  • 144
  • 161
19

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.

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
8

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012