[R] Appending results via for loop

Turchin, Michael Michael.Turchin at childrens.harvard.edu
Fri Feb 5 17:14:23 CET 2010


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


More information about the R-help mailing list