[R] Randomly remove condition-selected rows from a matrix
Charles C. Berry
cberry at tajo.ucsd.edu
Wed Dec 31 19:00:09 CET 2008
On Wed, 31 Dec 2008, Guillaume Chapron wrote:
>> I believe this does what you want:
>> m[-sample(which(m[,1]<8 & m[,2]>12),2),]
>> Get a boolean vector of rows fitting criteria:
>> m[,1]<8 & m[,2]>12
>> What are their indexes?
>> Choose two among those indexes:
> Thanks, but this does not seem to always work.
> Supposing I sample only one row among the ones matching my criteria. Then
> consider the case where there is just one row matching this criteria. Sure,
> there is no need to sample, but the instruction would still be executed. Then
> if this row index is 15, my instruction becomes which(15,1), and this can
I think you mean 'sample(15,1)', no?
If x has length 1, is numeric (in the sense of is.numeric) and x >= 1,
sampling takes place from 1:x. Note that this convenience feature may lead
to undesired behaviour when x is of varying length sample(x). See the
resample() example below.
So define and use 'resample'.
It often helps to reread help pages and rerun example()s, when things are
not going your way!
> gives me any row from 1 to 15, which is not correct. I have to make a
> condition in case there is only one row matching the criteria.
> R-help at r-project.org mailing list
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help