5

I'm trying to make a boxplot from the WeightLoss dataset from the car package. The variables of interest are separated by month, so I made boxplots by month separately, with all the groups (Control, Diet, Diet and Exercise) showing. I only want to get the boxplot of the group Diet and their weight loss across the span of 3 months in 1 boxplot instead of 3. To clarify, I need ylab="Weight loss" and xlab="Month" as my axes. I have no idea on how to do this though.

This is the first feasible set of boxplots I was able to make, but they're separated by month and all the groups show up in the boxplot.

library(car)
library(DescTools)

boxplot(wl1 ~ group, data=WeightLoss, 
        main="Weight Loss after 1 month",
        ylab="Weight loss",
        xlab="Group")
boxplot(wl2 ~ group, data=WeightLoss, 
        main="Weight Loss after 2 months",
        ylab="Weight loss",
        xlab="Group")
boxplot(wl3 ~ group, data=WeightLoss, 
        main="Weight Loss after 3 months",
        ylab="Weight loss",
        xlab="Group")

I tried to separate the group I only wanted like this:

boxplot(wl1 ~ group$Diet, data=WeightLoss,  
        main="Weight Loss after 1 month",
        ylab="Weight loss",
        xlab="Group")

but I keep on getting this error:

Error in group$diet : $ operator is 
    invalid for atomic vectors
kjetil b halvorsen
  • 1,206
  • 2
  • 18
  • 28

2 Answers2

2

Try

boxplot(wl1 ~ as.character(group),
         data= 
   WeightLoss[WeightLoss$group=="Diet", ],
         main="Weight Loss after 1 month",
         ylab="Weight loss",
         xlab="Group")

boxplot produced by the code above

kjetil b halvorsen
  • 1,206
  • 2
  • 18
  • 28
Bensstats
  • 988
  • 5
  • 17
2

We could first subset to diet group, then reshape the months into long format (cbinding an ID column first).

library(car)  ## to load `WeightLoss` data

subset(cbind(WeightLoss, id=seq_len(nrow(WeightLoss))), group == 'Diet') |>
  reshape(varying=c("wl1", "wl2", "wl3"), timevar='months', dir='long', sep='') |>
  boxplot(wl ~ months, data=_)

enter image description here

The plot shows the weight loss in the respective month.

jay.sf
  • 60,139
  • 8
  • 53
  • 110
  • Thanks for this! I'm curious, where does the `wl` object get formed? I would like to do another boxplot but using the self-esteem variable (se1, se2, se3). I'm not sure which to change? I changed `wl` to `se` and then again the object was not found. Any hints to get around this? Thanks! – struggling student Dec 19 '22 at 09:45
  • 1
    @strugglingstudent It's the `varying=` argument of `reshape`. Please see edit where I made it more explicit. It's actually better to use names instead of numbers, sorry for my laziness. – jay.sf Dec 19 '22 at 09:52