[R] subsetting matrix replacement oddities

Ross Boylan ross at biostat.ucsf.edu
Thu Sep 18 01:52:49 CEST 2003


When assigning a dataframe to a subset of a matrix I got a very odd
result.  Am I missing something, or is this a bug?  Details are below.

Also, if m is defined outside of the current function, is
m[...] <<- foo
necessary to update it, or does regular replacement
m[....] <- foo
work (that is, does it update the "global" rather than creating a
"local" that conceals it)?  I got conflicting results, which were
tangled up with the oddity below.
--------------------------------------------------------

Browse[1]> covs
    epilepsy other.cancer
680        0            0
681        0            0
682        0            0
683        0            1
684        0            0
Browse[1]> m <- matrix(NA, 5,2)
Browse[1]> m[,1:2] <- covs
Browse[1]> m
[[1]]
[1] 0 0 0 0 0

[[2]]
[1] 0 0 0 1 0

[[3]]
[1] 0 0 0 0 0

[[4]]
[1] 0 0 0 1 0

[[5]]
[1] 0 0 0 0 0

[[6]]
[1] 0 0 0 1 0

[[7]]
[1] 0 0 0 0 0

[[8]]
[1] 0 0 0 1 0

[[9]]
[1] 0 0 0 0 0

[[10]]
[1] 0 0 0 1 0

Browse[1]> dim(covs)
[1] 5 2
Browse[1]> class(covs)
[1] "data.frame"
Browse[1]> class(m)
[1] "list"
Browse[1]> length(m)
[1] 10

Fortunately, the following seems to work as expected:
Browse[1]> m[,1:2] <- as.matrix(covs)


Ross Boylan                                      wk:  (415) 502-4031
530 Parnassus Avenue (Library) rm 115-4          ross at biostat.ucsf.edu
Dept of Epidemiology and Biostatistics           fax: (415) 476-9856
University of California, San Francisco
San Francisco, CA 94143-0840                     hm:  (415) 550-1062




More information about the R-help mailing list