[R] Appending results via for loop
jim holtman
jholtman at gmail.com
Fri Feb 5 18:02:41 CET 2010
use a list:
result <- list()
for (i in 1:limit){
....computation....
# store results
result[[i]] <- yourData
}
On Fri, Feb 5, 2010 at 11:14 AM, Turchin, Michael
<Michael.Turchin at childrens.harvard.edu> wrote:
> Hey all,
>
> So I'm manually conducting a sliding window test, and I would like to tack on results to some variable as the results are outputted. I'm using a for loop, and I am currently using an array as my 'output collector' variable, though I know I should be using a dataframe of some sort. My question is how to properly initialize a dataframe, and then add results to it as I go through my for loop. Do I need to assign the size of the dataframe beforehand, or can it be dynamic? I've read the help files and the mailing lists, but I think I am not wording my question properly to find the right answers, so I'm opting for this instead : )
>
> Here's my code:
>
> window <- 50
> size <- 0
> if (length(counts2$Count)<length(counts1$Count)) { size <-length(counts2$Count) } else { size <- length(counts1$Count) }
> a <- 0
> b <- 0
> alpha <- .05
> n <- window
> pval <- qchisq((1-(alpha / n)), 1)
> results <- c(seq(1,size,window))
> loop <- 1
> for (i in seq(1,size,window)) {
>
> a <- i
> b <- i + window - 1
> countsavg <- (sum(abs(counts2$Count[a:b] - counts1$Count[a:b])))/length(a:b)
> countschisq <- ((abs(((counts2$Count[a:b] - counts1$Count[a:b])-countsavg))^2)/countsavg)
> results[loop] <- countschisq
> loop <<- loop + 1
>
> }
>
> I'm guessing I'll be getting rid of the loop variable and the 'per index' assignment thing, but I'm not sure what to do. Also, I'd like to actually be grabbing 3 different groups of value per window, rather than just one. So ultimately I'd like to have 3 columns in my data frame, and add to each column every time I go through the data frame.
>
> Thanks for your help everyone, really appreciate it,
> ~Michael
> ______________________________________________
> 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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list