r - Nested for loop (or possibly create a function) -
i doing basic plots exploratory analyses, , have created loop of work me. have 12 years of data, 5 different categories(cat1-cat5), , 3 different variables(say x,y,z). loops have done far gives me histogram of each of variables year (so x in year 1 - x in year 12 example).
i partitioned data in 2 ways - category, , year follows:
cat.1<-subset(data,category==1) #similar code categories 2-5 categories<-list(cat.1,cat.2,cat.3,cat.4,cat.5) year.1<-subset(data,year==1) years<-list(year.1,year.2, ... , year.12)
now, data partitioned way have set loops:
for(i in (1:length(categories)) { store.data<-categories[[i]] hist(store.data$x) }
what have external loop deals 3 variables:
variables<-list(x,y,z) for(j in (1:length(variables)) { #insert above loop here }
the desired output output of of histograms each year , each variable. realize can add in lines original loop:
hist(store.data$y) hist(store.data$z)
but, running analyses (anova, t-test, etc) on data , plan on having same setup. having external loop deals variable internal loop works on, should have less code write in theory.
this short solution gives histograms, doesn't name them inform histogram relate category. histograms named variable, , order histograms generated correspond numerical order of categories. doesn't you're labeling you're histograms in code posted, may not problem you.
category = rep(1:5,20) x = rnorm(100) y = rexp(100) z = rgamma(100,5) require(data.table) dt = data.table(category, x, y, z) dt[,lapply(.sd, hist), by=category]
Comments
Post a Comment