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
CodePudding user response:
We could first subset
to diet group, then reshape
the months into long format (cbind
ing 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=_)
The plot shows the weight loss in the respective month.
CodePudding user response:
Try
boxplot(wl1 ~ as.character(group),
data=
WeightLoss[WeightLoss$group=="Diet", ],
main="Weight Loss after 1 month",
ylab="Weight loss",
xlab="Group")