RE: [R] R: looping

From: Huntsinger, Reid <>
Date: Sat 21 May 2005 - 02:16:56 EST

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))


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-----
[] On Behalf Of Clark Allan Sent: Friday, May 20, 2005 10:01 AM
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)


for (i in 1:3) z[z[,i]>top[i]]<-top[i] mailing list PLEASE do read the posting guide! Received on Sat May 21 02:50:11 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:58 EST