0

When plotting in a loop in r, how do you call a variable that is not one of the plot variables (x or y)?

My dataset has the following fields: Level (y-value), CG(x-value), CatNum, and CatName. CatNum is the category number, and CatName is the corresponding name.

I have successfully created a box plot loop to make one plot for each unique CatNum. I want both CatNum and CatName to appear in the plot title, but have only been able to include CatNum. My attempt is below, but when I call the variable "name", it prints the entire CatName column, over top of the plot.

How do I call both CatNum and CatName for the current "cat" in the loop, so that the title will be "Category (CatNum) (CatName)"?

for (cat in unique(dataset$Category)){
  #d <- subset(dataset, Category==cat)
  name <- dataset$CatName
  boxplot(Level[Category==cat]~CG[Category==cat], data=dataset, xlab=" Group", 
          ylab="Level", main=paste("Category", CatNum, CatName), outline=FALSE)
}
  • If you can provide some sample data (either constructed with `data.frame` or output via `dput(head(dataset,n=20))` using a number like 20 to balance "too much in the question" with "sufficient to show enough groups), you are more likely to get a meaningful answer. – r2evans Oct 29 '18 at 18:56
  • I think you just want to use `main=paste("Category", cat) `, Your loop variable "cat" should be the name of the variable. From your question it is not clear what your desire output is. – Dave2e Oct 29 '18 at 19:06
  • @Dave2e Edited to make more clear. There is a corresponding CatNum for each CatName, and I want to print both. How do I print another variable from the dataset that is being looped through? – marmaluffalo Oct 29 '18 at 19:20
  • @r2evans edited to make more clear – marmaluffalo Oct 29 '18 at 19:21
  • marmaluffalo, you misunderstood my suggestion. Literally *give us some representative data*, not just a description of what you think the data looks like. A couple of reasons: (1) the data may not be exactly what you think it is; and (2) it is much easier for us to use representative data if you provide it verbatim. Also, it's best to reduce code; in this case, `pdf` and `dev.off` are tangential, unless you think the problem only presents when you save the plots to a file. (In that case, add a note you save to pdf to preclude comments of "boxplot in a loop is useless" :-) – r2evans Oct 29 '18 at 19:58
  • What r2evans is asking is that you post a [reproducible example](https://stackoverflow.com/a/5963610/2359523). – Anonymous coward Oct 29 '18 at 19:59
  • @r2evans I see what you are saying, but my question really boils down to: When looping through a dataset, how do you call a value from another field in the same row? I can only figure out how to call the entire field/column. – marmaluffalo Oct 29 '18 at 21:15

0 Answers0