In R, what does a negative index do?

I am moving part of the program (not enough to compile and run) from R to C ++. I am not familiar with R. I did everything correctly using online links, but was puzzled by the following line:

cnt2.2<-cnt2[,-1] 

I suppose:

  • cnt2 is a two-dimensional matrix
  • cnt2.2 is a new variable declared with the period '.' used in the same way as an alphabetic character.
  • <- is the destination.
  • [,-1] refers to the part of the array. I thought that [,5] means all rows, only the 5th column. If this is correct, I do not know what -1 refers to.
+12
source share
3 answers

This is described in section 2.7 of the manual: http://cran.r-project.org/doc/manuals/R-intro.html#Index-vectors

This is a negative index into the cnt2 object that defines all rows and all columns except the first column.

+19
source

Negative indices determine the deletion (not preservation) of certain elements ... therefore x[,-1] determines the deletion of the first column (rows are the first dimension before the decimal point, and columns are the second dimension after the decimal point). From ?"[" ( Http://stat.ethz.ch/R-manual/R-devel/library/base/html/Extract.html ):

Only for '[-indexing:' i, 'j,' ... there can be logical vectors indicating the elements / fragments to select. Such vectors are processed as necessary to fit the appropriate degree. 'I,' j, '... can also be negative integers, specifying elements / pieces to leave out of choice.

+14
source

1) cnt2 is a two-dimensional matrix

From the code you pointed out, it really is a 2-dimensional structure of some type (it’s quite possible the matrix).

2) cnt2.2 is a new variable declared with the period '.' used in the same way as an alphabetic character.

Correctly.

3) <- task.

Correctly.

4) [, -1] refers to the part of the array. I thought that [, 5] means all rows, only the 5th column. If this is correct, I do not know what -1 means.

[,-1] selects all columns except column 1. Note that, unlike C ++, indexes in R start from one, not from zero.

+6
source

All Articles