[Rd] Inconsistency in subset results

Saikat DebRoy saikat at stat.wisc.edu
Mon Oct 13 19:56:08 MEST 2003


Subsetting objects with attributes are present do not behave 
consistently.
The exception is the empty vector subscript.

Let's look at an example.

 > foo <- matrix(1:16, 4, dimnames=list(letters[1:4], letters[5:8]))
 > names(foo) <- LETTERS[1:16] # add names
 > attr(foo, 'bar') <- TRUE # and an extra attribute
 > foo
   e f  g  h
a 1 5  9 13
b 2 6 10 14
c 3 7 11 15
d 4 8 12 16
attr(,"names")
  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P"
attr(,"bar")
[1] TRUE
 > foo[] # returns the original object
   e f  g  h
a 1 5  9 13
b 2 6 10 14
c 3 7 11 15
d 4 8 12 16
attr(,"names")
  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P"
attr(,"bar")
[1] TRUE
 > foo[,] # but this does not
   e f  g  h
a 1 5  9 13
b 2 6 10 14
c 3 7 11 15
d 4 8 12 16
 > foo[1:16] # neither does this
  A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P
  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
 >

Basically, foo[] behaves differently from others. Every other subset 
operation drops attributes (other than those directly relevent).

In case anyone is wondering, for Splus (old 3.4 on a Sun), the results
are same for all but the matrix subset operation. Then we get

Splus3.4> foo[,]
   e f  g  h
a 1 5  9 13
b 2 6 10 14
c 3 7 11 15
d 4 8 12 16
attr(,"names")
  [1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P"

In fact if a names attribute is present, Splus always subsets it as if 
it was an array with same dimensions as the actual object.



More information about the R-devel mailing list