[R] Replacing several rows of a matrix at once

Joshua Wiley jwiley.psych at gmail.com
Mon Nov 29 05:05:47 CET 2010


Hi Bryan,

The reason vec gets recycled is that you are replacing more values
than vec has.  Just look at:

tmp[p, ]

this is 3 x 10 matrix, which you are trying to replace with a vector
of length 10.  If you want the replacement to occur without any
recycling, you'll need to make vec be a matrix itself or at least a
vector of length 30 (i.e., 3 * 10).  Or do you want it recycled but in
a different way than it is currently being recycled?  (see Michael's
response for that).

Cheers,

Josh

On Sun, Nov 28, 2010 at 7:53 PM, Bryan Hanson <hanson at depauw.edu> wrote:
> Hello Folks.  This must be a silly question with a (not) obvious (to me)
> answer.
>
> Consider this:
>
> tmp <- matrix(1:200, nrow = 20)
> vec <- 300:309
>
> tmp[9,] <- vec # replacing one row works fine
>
> p <- c(3, 11, 17)
> tmp[p,] <- vec
> # replacing multple rows pastes the values down a column and recycles vec.
>
> What I want to do is replace multiple rows simultaneously at once.  I
> suppose I can write a function, but this seems pretty fundamental so I feel
> I must be missing some obvious alternative.  I'm feeling like I'm in the
> Inferno!
>
> TIA.  Bryan
> *************
> Bryan Hanson
> Professor of Chemistry & Biochemistry
> DePauw University, Greencastle IN USA
>
>> sessionInfo()
> R version 2.12.0 (2010-10-15)
> Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
>
> locale:
> [1] en_US.UTF-8/en_US.UTF-8/C/C/en_US.UTF-8/en_US.UTF-8
>
> attached base packages:
>  [1] splines   datasets  tools     grid      grDevices graphics  utils
> stats
>  [9] methods   base
>
> other attached packages:
>  [1] survival_2.35-8    gridExtra_0.7      GGally_0.2.2       xtable_1.5-6
>  [5] mvbutils_2.5.1     ggplot2_0.8.8      proto_0.3-8        reshape_0.8.3
>  [9] ChemoSpec_1.46     seriation_1.0-2    colorspace_1.0-1   TSP_1.0-1
> [13] R.utils_1.5.3      R.oo_1.7.4         R.methodsS3_1.2.1  rgl_0.92.794
> [17] lattice_0.19-13    mvoutlier_1.4      plyr_1.2.1
> RColorBrewer_1.0-2
> [21] chemometrics_1.0   som_0.3-5          robustbase_0.5-0-1 rpart_3.1-46
> [25] pls_2.1-0          pcaPP_1.8-3        mvtnorm_0.9-92     nnet_7.3-1
> [29] mclust_3.4.6       MASS_7.3-8         lars_0.9-7         gclus_1.3
> [33] cluster_1.13.1     e1071_1.5-24       class_7.3-2
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list