[R] barplot in a loop not printing out to directory

Dimitri Liakhovitski ld7631 at gmail.com
Sat May 16 14:43:42 CEST 2009


Hello!
I am experiencing a problem with section 3 of the code below. I want
to generate barplots (based on data generated in Sections 1 and 2) in
a loop - for each variable in "data" - and save them as .emf files in
my current directory. But it's not working - it's printing values to
be plotted to the screen but does not print the plots themselves
anywhere (and not in the directory).
Thank you very much for your help!
Dimitri

### Section 1. This section generates my data set "data" - no problems there:

N<-100
myset1<-c(1,2,3,4,5)
probs1<-c(.05,.10,.15,.40,.30)
myset2<-c(0,1)
probs2<-c(.65,.30)
myset3<-c(1,2,3,4,5,6,7)
probs3<-c(.02,.03,.10,.15,.20,.30,.20)

group<-as.factor(sapply(1:4,function(x){
	out<-rep(x,25)
	out
}))
set.seed(1)
a<-sample(myset1, N, replace = TRUE,probs1)
a[which(rbinom(100,2,.01)==1)]<-NA
set.seed(12)
b<-sample(myset1, N, replace = TRUE,probs1)
b[which(rbinom(100,2,.01)==1)]<-NA
set.seed(123)
c<-sample(myset2, N, replace = TRUE,probs2)
set.seed(1234)
d<-sample(myset2, N, replace = TRUE,probs2)
set.seed(12345)
e<-sample(myset3, N, replace = TRUE,probs3)
e[which(rbinom(100,2,.01)==1)]<-NA
set.seed(123456)
f<-sample(myset3, N, replace = TRUE,probs3)
f[which(rbinom(100,2,.01)==1)]<-NA
data<-data.frame(group,a=a,b=b,c=c,d=d,e=e,f=f)

### Section 2. Generating tables with percentages for barplot:
tables<-lapply(data,function(x){
	out<-table(x)
	out<-prop.table(out)
	out<-round(out,3)*100
	out.df<-data.frame(matrix(nrow=length(out),ncol=2))
	names(out.df)<-c("Value","Percentages")
	out.df[1]<-dimnames(out)[1]
	out.df[2]<-out
	return(out.df)
})
(tables)

### Section 3. I want to generate a barplot based on each and every
table I produced above and put it in my current directory. But it's
not working.

for(i in 1:length(tables)) {
	chart.name<-names(data)[i]
	filename=paste(i,chart.name,"emf",sep=".")
	win.metafile(file=filename)
	chart<-barplot(tables[[i]][[2]],xlab = "Values", ylab =
"Percentages",ylim=c(0,100))
	print(chart)
	dev.off()
}

Thank you very much!
-- 
Dimitri Liakhovitski
MarketTools, Inc.
Dimitri.Liakhovitski at markettools.com




More information about the R-help mailing list