[R] R: looping
Huntsinger, Reid
reid_huntsinger at merck.com
Fri May 20 18:16:56 CEST 2005
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[z[,i]>top[i]]<-top[i]
More information about the R-help
mailing list