Reputation: 28309
I am asking question that was probably asked before. However, I was not able to find answer that I could adjust to my data.
Example of my data:
State V1 V2 V3
2 0.00000 0.0000 12.2661
4 0.00000 0.0000 21.3610
3 2.15633 0.0000 0.0000
3 28.07880 33.0049 30.7882
2 0.00000 0.0000 0.0000
6 0.00000 7.3000 33.6100
2 1.00000 0.0000 10.2503
4 0.00000 5.0000 56.3410
3 2.15633 0.0000 0.0000
6 8.07880 43.0049 15.8002
2 0.40000 0.0000 0.0000
2 0.00000 0.0000 23.1000
I want to: for every State
(2,3,4,6), plot every Variable
(V1,V2,V3).
I am able to get want I want using this code:
s2 <- subset(df, State == 2)
s3 <- subset(df, State == 3)
s4 <- subset(df, State == 4)
s6 <- subset(df, State == 6)
jpeg('rplot_V1.jpg')
boxplot(s2$V1,s3$V1,s4$V1,s6$V1)
dev.off()
jpeg('rplot_V2.jpg')
boxplot(s2$V2,s3$V2,s4$V2,s6$V2)
dev.off()
jpeg('rplot_V3.jpg')
boxplot(s2$V3,s3$V3,s4$V3,s6$V3)
dev.off()
This solution is clumsy when data-frame is 10 times larger.
My question: How to loop over the data frame and print?
Upvotes: 1
Views: 130
Reputation: 56004
Try this:
#dummy data
df <- read.table(text="State V1 V2 V3
2 0.00000 0.0000 12.2661
4 0.00000 0.0000 21.3610
3 2.15633 0.0000 0.0000
3 28.07880 33.0049 30.7882
2 0.00000 0.0000 0.0000
6 0.00000 7.3000 33.6100
2 1.00000 0.0000 10.2503
4 0.00000 5.0000 56.3410
3 2.15633 0.0000 0.0000
6 8.07880 43.0049 15.8002
2 0.40000 0.0000 0.0000
2 0.00000 0.0000 23.1000", header=TRUE,as.is=TRUE)
#plot boxplot
lapply(2:ncol(df),function(i){
jpeg(paste0(paste("State",colnames(df)[i],sep="~"),".jpeg"))
boxplot(df[,i]~df$State,
ylab="State",
xlab=colnames(df)[i],
main=paste("State",colnames(df)[i],sep="~"))
dev.off()
})
Upvotes: 1
Reputation: 70256
I think this is what you are after
states <- unique(test$State) #if your data.frame is called `test`
for(i in 1:length(states)){
boxplot(test[test$State == states[i],2:4])
}
Edit after comment by OP
If you want to plot states 1, 2 and >=3 you can easily do this by temporarily creating another data.frame (tmp) and manipulate the State values. Then you can just use the same loop as described above.
tmp <- test
tmp$State[tmp$State >= 3] <- 3
states <- unique(tmp$State)
for(i in 1:length(states)){
boxplot(test[test$State == states[i],2:4])
}
Upvotes: 1