0

Aim create bar chart where xaxis=day, yaxis=mass and fill=group

I have used pivot wider to get the data into a usable format. However I am stuck on how to summarise the data for inputing it into the bar chart - when i try and use summarise i get one summary statistic despite grouping by day and group

study_id <- c(1,2,3,4,5,6)
group <- c(1,2,1,2,1,2)
mass_day1 <-c(NA,2,NA,3,NA,1)
mass_day2 <- c(15,15,15,15,NA,15)
mass_day3 <-c(3,3,3,3,3,3)
mass_day4 <- c(4,4,4,NA,4,4)

drink_df  <- data.frame(study_id,group,mass_day4,mass_day3,mass_day2,mass_day1) 

drink_dfa <- drink_df %>%   
  pivot_longer(cols = starts_with("mass"),       
               names_to = c(".value", "day"),    
               names_pattern = '(.*)_(.*)',
               values_drop_na = TRUE) %>% 
  dplyr::group_by(day,group) %>% summarise(
  mass = mean(mass), na.rm = TRUE) %>% ungroup()
  
plot <- ggplot(drink_dfa, aes(x = day, y = mass, fill = group)) +
geom_bar(stat="identity", position=position_dodge(), na.rm = FALSE)
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
GJW
  • 105
  • 6
  • 4
    Your `group` is numeric, so the fill is a continuous color scale. You probably want `group=factor(1,2,1,2,1,2)`. – James_D Apr 28 '23 at 14:28
  • 4
    Maybe try `dplyr::summarize`. Your code works for me. I see `drink_dfa` is a tibble with 7 rows and 4 columns. Do you have other packages like `plyr` loaded as well? – MrFlick Apr 28 '23 at 14:32
  • 3
    @James_D, correction, `factor(c(1,2,1,2,1,2))`, without the `c(..)` vector it returns a length-1 `NA` factor. – r2evans Apr 28 '23 at 15:06
  • 3
    GJW, if you're also using `plyr`, see https://stackoverflow.com/q/26106146/3358272 to see why you should either load `plyr` _before_ `dplyr` or force which function you intend by using `dplyr::summarize` (instead of R inferring `plyr::summarize`, a different function). – r2evans Apr 28 '23 at 15:35
  • Thank you. dplyr::summarize solved the issue - recently started using another package that loaded plyr – GJW Apr 30 '23 at 02:40

0 Answers0