Skip to content
Back to formatted view

Raw Message

Message-ID: <510DABCE.7030908@sapo.pt>
Date: 2013-02-03T00:14:06Z
From: Rui Barradas
Subject: vectorisation
In-Reply-To: <E642527740AD6A45B6AEBCC7A7E4C39C065C662D7F@THHS2E12BE5X.hostedservice2.net>

Hello,

Try the following.

set.seed(4315)
ml <- data.frame(matrix(sample(1:50,80, replace=TRUE),20,4))
mm <- apply(ml, 2, cumsum)
s2 <- starts <- data.frame(matrix(0,600,4))

for (i in 1:4){
	starts[,i][mm[,i]] <- 1
}

s2[] <- lapply(seq_len(ncol(mm)), function(i) {s2[,i][mm[,i]] <- 1; s2[,i]})

identical(s2, starts) # TRUE


Note that lapply is a loop in disguise.

Hope this helps,

Rui Barradas

Em 02-02-2013 16:38, Brett Robinson escreveu:
> Hi
> I'm trying to set up a simulation problem without resorting to (m)any loops. I want to set entries in a data frame of zeros ('starts' in the code below) to 1 at certain points and the points have been randomly generated and stored in a separate data.frame ('sl'), which has the same number of columns.
>
> An example of the procedure is as follows:
> ml <- data.frame(matrix(sample(1:50,80, replace=TRUE),20,4))
> mm <- apply(ml, 2, cumsum)
> starts<- data.frame(matrix(0,600,4))
>
> I can achieve the result I want with a loop:
> for (i in 1:4){
> lstarts[,i][mm[,i]] <-1
> }
>
> But as I want to use a large number of columns I would like to do away with the loop
>
> Can anyone suggest how this might be done?
>
> Thanks in advance
>
> Brett Robinson
>
> ______________________________________________________________________
> This email has been scanned by the Symantec Email Security.cloud service.
> For more information please visit http://www.symanteccloud.com
> ______________________________________________________________________
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>