[R] Change a value in a matrix randomly

Peter Alspach Peter.Alspach at plantandfood.co.nz
Tue Nov 9 23:22:15 CET 2010


Tena koe Judit

If it is really a matrix (and not a data.frame) and you wish to change a randomly selected zero to a one, then

judit <- matrix(0, nrow=3, ncol=4)
judit[sample(1:length(judit), 1)] <- 1

will do.  This uses the fact that a matrix is a vector with a dim attribute.

HTH ....

Peter Alspach

> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Barroso, Judit
> Sent: Wednesday, 10 November 2010 10:50 a.m.
> To: r-help at r-project.org
> Subject: [R] Change a value in a matrix randomly
> 
> I have a matrix of ceros, for example:
> 0              0              0              0
> 0              0              0              0
> 0              0              0              0
> And I would like that one of these values turn into 1, for example if
> one condition is got, but not in a concrete position if not randomly.
> Could you indicate me the code to can get it?
> 
> Thanks in advance,
> Judit Barroso
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> 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.

The contents of this e-mail are confidential and may be subject to legal privilege.
 If you are not the intended recipient you must not use, disseminate, distribute or
 reproduce all or any part of this e-mail or attachments.  If you have received this
 e-mail in error, please notify the sender and delete all material pertaining to this
 e-mail.  Any opinion or views expressed in this e-mail are those of the individual
 sender and may not represent those of The New Zealand Institute for Plant and
 Food Research Limited.



More information about the R-help mailing list