try this: > test2 <- rep(seq(1:5),2000) > #setup a data frame and index into the columns > result <- data.frame(event1=rep(0,length(test2)), event2=rep(0,length(test2)), + event3=rep(0,length(test2)), event4=rep(0,length(test2)), event5=rep(0,length(test2))) > for (i in seq(ncol(result))){ + result[[i]] <- ifelse(test2 == i, 1, 0) + } > > str(result) 'data.frame': 10000 obs. of 5 variables: $ event1: num 1 0 0 0 0 1 0 0 0 0 ... $ event2: num 0 1 0 0 0 0 1 0 0 0 ... $ event3: num 0 0 1 0 0 0 0 1 0 0 ... $ event4: num 0 0 0 1 0 0 0 0 1 0 ... $ event5: num 0 0 0 0 1 0 0 0 0 1 ...
On 12/29/06, sj <[EMAIL PROTECTED]> wrote: > > I am working with a dataset where there are 5 possible outcomes (coded > 1:5), > I would like to create 5 categorical variables (event1...event5). I am > using > a for loop an if statements, but I have a large dataset( approx 100,000 > rows) it takes quite a bit of time, is there a way to speed this up? Here > is > some sample code of what I am currently doing. > > test2 <-rep(seq(1:5),2000) > > event1 <- rep(0,nrow(test2)) > event2 <- rep(0,nrow(test2)) > event3 <- rep(0,nrow(test2)) > event4 <- rep(0,nrow(test2)) > event5 <- rep(0,nrow(test2)) > > for(i in 1:length(event1)) > { > if (test2[i]==1) > { > event1[i]=1 > } > > if (test2[i]==2) > { > event2[i]=1 > } > > if (test2[i]==3) > { > event3[i]=1 > } > > if (test2[i]==4) > { > event4[i]=1 > } > > if (test2[i]==5) > { > event5[i]=1 > } > } > > > > thanks, > > Spencer > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help@stat.math.ethz.ch 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. > -- Jim Holtman Cincinnati, OH +1 513 646 9390 What is the problem you are trying to solve? [[alternative HTML version deleted]] ______________________________________________ R-help@stat.math.ethz.ch 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.