[R] yet another vectorization question

Adrian Dusa adi at roda.ro
Mon Jan 30 21:09:18 CET 2006


On Monday 30 January 2006 21:44, Patrick Burns wrote:
> I tried to let this pass, but failed:
>
> lapply(1:3, function(x) c(0, 1, NA))
>
> might more clearly be written as
>
> rep(list(c(0, 1, NA)), 3)

Indeed! Excellent, thanks :)

Hmm, I was just thinking perhaps my first example was too cluttered to spot an 
immediate solution.
With your permission, I came up with a simpler example (I hope I don't upset 
anybody being too persistent):

set.seed(5)
aa <- matrix(sample(10, 15, replace=T), ncol=5)
bb <- matrix(NA, ncol=10, nrow=5)
for (i in 1:ncol(aa)) bb[i, aa[, i]] <- c(0, 1, 0)

Is there any possibility to vectorize this "for" loop?
(sometimes I have hundreds of columns in the "aa" matrix)

Many big thanks in advance,
Adrian

-- 
Adrian DUSA
Romanian Social Data Archive
1, Schitu Magureanu Bd
050025 Bucharest sector 5
Romania
Tel./Fax: +40 21 3126618 \
          +40 21 3120210 / int.101




More information about the R-help mailing list