# [R] Re: [S] Putting values into matrices: desired behaviour?

Martin Maechler maechler at stat.math.ethz.ch
Wed Sep 1 09:30:01 CEST 1999

```>>>>> On Wed, 01 Sep 1999 08:34, Mette Langaas <Mette.Langaas at nr.no> said:

Mette> I'm running S-Plus 5.1 on UNIX (but the same behaviour I'm
Mette> describing is seen on S-Plus 3.4 R1 for UNIX).

Mette> I have first created a matrix with two rows and three columns

>> test_matrix(ncol=3,nrow=2)
>> test
Mette>       [,1] [,2] [,3]
Mette> [1,]   NA   NA   NA
Mette> [2,]   NA   NA   NA

Mette> I then want to put values into parts of the matrix, but by mistake I
Mette> index outside the matrix (use rows 3-7 when there are only 2 rows).

>> ind_matrix(c(1,2,3,4,5,6,7,2,2,2,2,2,2,2),ncol=2)
>> ind
Mette>      [,1] [,2]
Mette> [1,]    1    2
Mette> [2,]    2    2
Mette> [3,]    3    2
Mette> [4,]    4    2
Mette> [5,]    5    2
Mette> [6,]    6    2
Mette> [7,]    7    2
>> test[ind]_c(3,4,5,6,7,8,9)
>> test
Mette>       [,1] [,2] [,3]
Mette> [1,]   NA    3    5
Mette> [2,]   NA    4    6

Mette> The first observation is that in addition to correctly putting
Mette> values 3 ang 4 into position (1,2) and (2,2) the value 5 is put
Mette> into (1,3) instead of (3,2) as requested and
Mette> 6 is put into (2,3) instead of (4,3) as requested.

<...snip...>

Mette> Is this the desired behaviour of indexing matrices? What
Mette> measures can I take to avoid this behaviour -- e.g. to instead
Mette> get an error message?

In R, you do get an error message
``Error: subscript out of bounds''
and  test[,] remains unaltered.

I hope nobody complains about non-compatibility with S...  ;-)

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```