[R] R: looping

Clark Allan Allan at STATS.uct.ac.za
Fri May 20 18:25:19 CEST 2005


sorry everyone

the previous code seems to have been wrong. this is the corrected code
ie the last line


z<-matrix(c(1:9),3,3)
top<-c(1.5,5.5,9)

for (i in 1:3)  z[,i][z[,i]>top[i]]<-top[i]

/
allan


"Huntsinger, Reid" wrote:
> 
> Are you sure that's what you want to do? The subscript is a logical vector
> of length 3, subscripting a 3 x 3 matrix, so you're treating the matrix as a
> vector (stacked columns) and recycling the indices. The first iteration
> modifies 6 entries of the matrix.
> 
> It looks like you want to replace the entries in the ith column which exceed
> top[i] by top[i] (lost the ",i" in the subscript expression in copying,
> perhaps). That could be done in several ways. You can either create a matrix
> out of top of the same shape as z and then compare element-by-element, with
> pmin for example, or use the recycling rule. That latter is cleaner if z is
> transposed, but
> 
> > t(pmin(t(z),top))
> 
> works.
> 
> You could use apply as well, like
> 
> > apply(z,1,function(x) pmin(x,top))
> 
> to compare each row with the vector top, but you have to transpose the
> result. I don't see any advantage to this, though.
> 
> Reid Huntsinger
> 
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Clark Allan
> Sent: Friday, May 20, 2005 10:01 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] R: looping
> 
> hi all
> 
> i have a simple question. code is displayed below.
> 
> how can i use a vectorised command in order to do this (ie replace the
> loop)? (ie apply, lapply, sweep, etc)
> 
> z<-matrix(c(1:9),3,3)
> top<-c(1.5,5.5,9)
> 
> for (i in 1:3)  z[,i][z[,i]>top[i]]<-top[i]
> 
> ------------------------------------------------------------------------------
> Notice:  This e-mail message, together with any attachment...{{dropped}}



More information about the R-help mailing list