[R] which() and value replacement in a matrix

Liaw, Andy andy_liaw at merck.com
Sat Oct 9 15:00:22 CEST 2004


Use the index vector directly, rather than breaking it up:

> x <- matrix(sample(30), 10, 3)
> idx <- which(x > 25, arr.ind=TRUE)
> idx
     row col
[1,]   6   1
[2,]   9   1
[3,]   4   2
[4,]   6   2
[5,]   4   3
> x[idx] <- 999
> x
      [,1] [,2] [,3]
 [1,]    7   14   16
 [2,]   20   24    8
 [3,]   17   18   11
 [4,]   19  999  999
 [5,]   23    4   15
 [6,]  999  999    5
 [7,]   21    9   12
 [8,]   22    2    3
 [9,]  999   13    1
[10,]    6   10   25

HTH,
Andy

> From: Patrick Giraudoux
> 
> Hi,
> 
> I cannot go through the archives with which() as key-word... 
> so common. Though I am sure to have seen something about this subject
> in the past could somebody put me on the track. I have a 
> matrix (actually a data.frame) in which I would replace the 
> non-null values
> by 1.
> 
> I tried the following:
> 
> indices<-which(myforetbin > 0,arr.ind=T)
> myforetbin[indices[,1],indices[,2]]<-1
> 
> and get the message:
> 
> > myforetbin[indices[,1],indices[,2]]<-1
> Error in "[<-.data.frame"(`*tmp*`, indices[, 1], indices[, 
> 2], value = 1) :
>         duplicate subscripts for columns
> 
> I get the same with
> 
> myforetbin[indices]<-1
> 
> However, with:
> 
> myforetbin[indices]
> 
> I well get a vector with the corresponding non-null values.
> 
> Can somebody put me on the track?
> 
> All the best,
> 
> Patrick
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list