[R] strange behavior of matrix

William Revelle lists at revelle.net
Tue Apr 6 01:37:50 CEST 2010


Dear R list,

I have discovered a seemingly peculiar feature when using a matrix to 
index itself (yes, this is strange code, which I have now modified to 
be more reasonable).

  #this makes sense
  s <- matrix(1:3,nrow=1)
  s[s]    #all three elements are shown

  #but when I try
  s <- matrix(1:2,nrow=1)
  s[1]     #fine, the first element is shown
  s[2]     #fine, the second element is shown
  s[s]     #just the second element is shown  -- this is peculiar


  #But doing it by columns works for both cases
  s <- matrix(1:3,ncol=1)
  s[s]    #all three elements are shown


  #and when I try the same problem down a column
  s <- matrix(1:2,ncol=1)
  s[1]     #fine

  s[2]     #fine

  s[s]     #this shows both elements  as would be expected

  #clearly since I have just one dimension, it would have been better to
  s <- 1:2
  s[s]   #which works as one would expect.

Or, using the array  function we get the same problem.

>  s <- array(1:2,dim=c(1,2))
>  s[s]
[1] 2
>  s <- array(1:2,dim=c(2,1))
>  s[s]
[1] 1 2


>  sessionInfo()
R version 2.11.0 Under development (unstable) (2010-03-24 r51389)
i386-apple-darwin9.8.0

locale:
[1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] psych_1.0-87
>

I think this is unexpected behavior.

Best wishes,

Bill


-- 
William Revelle		http://personality-project.org/revelle.html
Professor			http://personality-project.org
Department of Psychology             http://www.wcas.northwestern.edu/psych/
Northwestern University	http://www.northwestern.edu/
Use R for psychology                       http://personality-project.org/r
It is 6 minutes to midnight	http://www.thebulletin.org



More information about the R-help mailing list