Boxplot and split in r

Viewed 41

I have a dataframe called Insectsprays that has two columns, count and spray. When I try to use split to create boxplots for each value of spray, I get the error shown below.

Can anyone explain the error for me? It's no doubt clear I'm new to R.

#
class(InsectSprays)
[1] "data.frame"

#
head(InsectSprays)  
  count spray   
1    10     A   
2     7     A   
3    20     A   
4    14     A   
5    14     A   
6    12     A   

#
boxplot(split(x=InsectSprays,f=InsectSprays$spray))  
Error in sort.int(x, na.last = na.last, decreasing = decreasing, ...) :   
  'x' must be atomic
1 Answers

boxplot expects a basic ('atomic') object like a series of numbers 1:10 or a list of basic atomic objects list(1:10,2:11). Your split produces a list of data.frames which boxplot doesn't know how to handle. Luckily, boxplot can also take a formula if you want to get results per group, like:

boxplot(count ~ spray, data=InsectSprays)

If you were working with a different function that didn't have this possibility, you would need to loop over the split list. Possibly something like:

## divide the plot window into 3 columns/2 rows
par(mfrow=c(2,3))
## loop over each object and `boxplot` the `count` column
lapply(split(InsectSprays, InsectSprays$spray), \(x) boxplot(x$count) )
Related