Skip to content

Instantly share code, notes, and snippets.

@atomicules
Created November 20, 2011 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save atomicules/1380293 to your computer and use it in GitHub Desktop.
Save atomicules/1380293 to your computer and use it in GitHub Desktop.
R and data.table for loop bug/nuance. Code extract for embedding in a blog post
#Extract of R code
#This doesn't work properly
#Need to know how many levels
nl <- length(levels(datatable$Grouping))
#then how many per graph
ng = 8
#Can then loop
for (i in 1:ceiling(nl/ng)) {
print(
xyplot(Y ~ Date | Grouping, datatable[levels(datatable$Grouping)[(i-1)*ng+1:(i*ng)]], layout=c(1,ng), ylim=c(-100,100), xlim=as.Date(c("2011-01-01", "2011-07-01")) )
)
}
#Instead of using the start and end variables within the loop, the values are calculated directly
#as applied to the datatable. For some reason, from the 2nd loop onwards, `i*ng` seems to be
#evaluated as `(i+1)*ng` which means Lattice automatically produces two pages of graphs, instead
#of just the one page per loop that it should.
#This is probably just a data.table nuance actually, not a bug.
#Extract of R code
#This works as expected
#Need to know how many levels
nl <- length(levels(datatable$Grouping))
#then how many per graph
ng = 8
#Can then loop
for (i in 1:ceiling(nl/ng)) {
start=(i-1)*ng+1
end=i*ng
print(
xyplot(Y ~ Date | Grouping, datatable[levels(datatable$Grouping)[start:end]], layout=c(1,ng), ylim=c(-100,100), xlim=as.Date(c("2011-01-01", "2011-07-01")) )
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment