2

I have this data frame:

df <- data.frame(make = c("dodge", "dodge", "toyota", "ford", "dodge", "toyota","toyota","ford",  "ford", "dodge"),
                  grn = c(    1,      1,        NA,      1,     NA,      NA,       1,         1,      NA,      NA),
                  blu = c(    NA,     NA,       1,       NA,    1,       NA,       NA,        NA,     1,       NA),
                  blk = c(    NA,     NA,       NA,      NA,    NA,      1,        NA,        NA,     NA,       1))   

I am trying to create a plot with "make" on the x-axis and the total "make" count for the y-axis and fill using the colors. I think I need to make a count table for the make and color but am unsure how to do this. For example the table would look something like this:

 DF <- read.table(text = "make  grn  blu  blk
                          dodge  2    1    1
                          ford   2    1    0
                          toyota 1    1    1", header = TRUE)

Then the solution is pretty straight forward

library(reshape2)
library(ggplot2)

DF1 <- melt(DF, id.var="make")

ggplot(DF1, aes(x = make, y = value, fill = variable)) +
geom_bar(stat = "identity")

So how can I transform my data frame "df" into "DF"?

2 Answers 2

3

Well you don't have to make all these transformation. The shorter way of making plot:

df %>%
  gather(key=col, value=num, -make) %>%
  na.omit() %>%
  ggplot(aes(make, fill=col)) +
    geom_bar()

First three rows create the long form of the input data. Then it is passed to ggplot to make the statistical transformations for you.

2

You can use dplyr::summarise_all:

library(dplyr)
df %>% group_by(make) %>% summarise_all(sum, na.rm=TRUE)

# A tibble: 3 × 4
#    make   grn   blu   blk
#  <fctr> <dbl> <dbl> <dbl>
#1  dodge     2     1     1
#2   ford     2     1     0
#3 toyota     1     1     1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.