[R] Randomly remove condition-selected rows from a matrix

Daniel Malter daniel at umd.edu
Tue Dec 30 16:30:38 CET 2008


Hi,

The approach below uses a function. The nice thing about it is that you can
define the cutoff values dynamically (i.e. what is 8 and 12 in your
example). The functions extract a row index to remove. Be aware that there
is no warning if both return the same row index. You might have to adjust
for that.

x=1:10
y=11:20
z=cbind(x,y)

a=function(x,m){which(x==sample(x[x<m],1))}
b=function(y,n){which(y==sample(y[y>n],1))}

z[-c(a(x,8),b(y,12)),]

Cheers,
Daniel




Guillaume Chapron-3 wrote:
> 
> Hello all,
> 
> I create the following matrix:
> 
> m <- matrix(1:20, nrow = 10, ncol = 2)
> 
> which looks like:
> 
>        [,1] [,2]
>   [1,]    1   11
>   [2,]    2   12
>   [3,]    3   13
>   [4,]    4   14
>   [5,]    5   15
>   [6,]    6   16
>   [7,]    7   17
>   [8,]    8   18
>   [9,]    9   19
> [10,]   10   20
> 
> Then, I want to remove randomly 2 rows among the ones where m[,1]<8  
> and m[,2]>12
> 
> I suppose the best way is to use the sample() function. I understand  
> how to do it when I remove among any rows, but I have not been able to  
> do it when I remove among specific rows only. What I could do is split  
> the matrix into two matrices, one with the rows to be sampled and  
> removed, one with the other rows. I would sample and remove, and then  
> merge the two matrices again. But since this part of the code is going  
> to be done many times, I would like to have it the most efficient  
> possible without creating new objects. Any idea? Thanks!
> 
> Cheers
> 
> Guillaume
> 
> ______________________________________________
> 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.
> 
> 

-- 
View this message in context: http://www.nabble.com/Randomly-remove-condition-selected-rows-from-a-matrix-tp21218219p21218541.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list