Search code examples
rdataframeflextable

Designating Headers in Flextable from Data frame


I have a tibble with Station Codes, Species, Days Present and Percent of Days present

tibble <- data.frame(
  station_code = c("A", "B", "A", "B", "A", "B"),
  species_name = c("Species1", "Species1", "Species2", "Species2", "Species3", "Species3"),
  days_present = c(10, 15, 20, 25, 30, 35),
  percent_days_present = c(50, 75, 80, 90, 60, 70))

I'd like to make a flextable that looks like this (data wise, not style):

enter image description here

EDIT: for reasons I don't understand, my original test data was not close enough to my actual data. This is the more accurate data

tibble2 <- data.frame(
  station_code = c("A","A","A","A","B","B","B","B"),
  species_name = c("Species1", "Species2", "Species3", "Species4", "Species1", "Species2", "Species3", "Species4"),
  days_present = c(10,15,20,25,30,35,20,35),
  percent_days_present = c(50,75,80,90,60,70,25,45))

Solution

  • If you want a flextable like that:

    library(dplyr)
    library(flextable)
    
    
    df %>% 
      arrange(species_name) %>% 
      rename(Station = "station_code", `Days Present` = "days_present", 
             `% Days Present` = "percent_days_present") %>% 
      as_grouped_data(., groups = "species_name", columns = NULL) %>% 
      as_flextable(hide_grouplabel = TRUE) %>% 
      set_header_labels(what = "") %>% 
      bold( bold = TRUE, part="header") %>% 
      align(i = ~ !is.na(species_name), align = "center") %>% 
      bold(i = ~ !is.na(species_name)) %>% 
      width(., width = 1.5)
    

    But if you just want to split your data:

    split(subset(df, select=-species_name), df$species_name, drop = T)
    #> $Species1
    #>   station_code days_present percent_days_present
    #> 1            A           10                   50
    #> 2            B           15                   75
    #> 
    #> $Species2
    #>   station_code days_present percent_days_present
    #> 3            A           20                   80
    #> 4            B           25                   90
    #> 
    #> $Species3
    #>   station_code days_present percent_days_present
    #> 5            A           30                   60
    #> 6            B           35                   70
    

    Data:

    df <- data.frame(
      station_code = c("A", "B", "A", "B", "A", "B"),
      species_name = c("Species1", "Species1", "Species2", "Species2", "Species3", "Species3"),
      days_present = c(10, 15, 20, 25, 30, 35),
      percent_days_present = c(50, 75, 80, 90, 60, 70))
    

    Created on 2023-11-17 with reprex v2.0.2