-1

I am new to R, and I am trying to figure out a problem for a class I am taking. I have one numerical variable (Bwt) and a categorical variable (Sex). I can make a simple boxplot with Sex on the x axis and Bwt on the y axis:

boxplot(Bwt ~ Sex)

What I need is to have Sex on the y axis and Bwt on the x axis, but it keeps saying it cannot because Sex is non-numerical (2 factors: M and F, in the dataset).

I also tried using ggplot2, and geom_boxplot + coord_flip and it gives me NULL with no boxplot at all. I know this is probably really simple to do, but I just can't figure it out! Is there a way for R to read my categorical variable as numeric or just an easier way? Thanks so much!

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
Jackie Reuder
  • 21
  • 1
  • 3
  • 2
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Axeman Aug 28 '18 at 06:02
  • 1
    A quick look at `?boxplot` reveals that there is a `horizontal` parameter, that one can set to `TRUE`. Your ggplot2 strategy _should_ work, but I can't tell what would be wrong with it since you aren't showing us any code or a reproducible example. – Axeman Aug 28 '18 at 06:05

1 Answers1

-1

Not sure where is the problem as you do not provide sample data. But hope this help:

set.seed(123)
df <- data.frame(Bwt = rnorm(100),
                 Sex = sample(c("M", "F"), 100, replace = T))

library(ggplot2)

ggplot(df, aes(x = as.factor(Sex), y = Bwt)) +
  geom_boxplot() + 
  coord_flip()

enter image description here

And there is solution with base boxplot:

boxplot(Bwt ~ Sex, data = df, horizontal = T)

enter image description here

Adela
  • 1,757
  • 19
  • 37