Chapter 8 Functions

load("data/metagenomics/data.Rdata")
#Aggregate GIFT at three hierarchical levels
GIFTs_elements <- to.elements(genome_gifts,GIFT_db)
GIFTs_functions <- to.functions(GIFTs_elements,GIFT_db)
GIFTs_domains <- to.domains(GIFTs_functions,GIFT_db)

#Calculate community-level traits
GIFTs_elements_community <- to.community(GIFTs_elements,
                                         genome_counts_row <- genome_counts %>%
                                            column_to_rownames(., "genome")  %>% 
                                            tss(),
                                         GIFT_db)
GIFTs_functions_community <- to.community(GIFTs_functions,
                                         genome_counts_row <- genome_counts %>%
                                            column_to_rownames(., "genome")  %>% 
                                            tss(),
                                         GIFT_db)
GIFTs_domains_community <- to.community(GIFTs_domains,
                                         genome_counts_row <- genome_counts %>%
                                            column_to_rownames(., "genome")  %>% 
                                            tss(),
                                         GIFT_db)
GIFTs_elements_community %>%
    as.data.frame() %>%
    rownames_to_column(var="sample") %>%
    pivot_longer(!sample,names_to="trait",values_to="gift") %>%
    left_join(sample_metadata, by = join_by(sample == sample)) %>%
    mutate(functionid = substr(trait, 1, 3)) %>%
    mutate(trait = case_when(
      trait %in% GIFT_db$Code_element ~ GIFT_db$Element[match(trait, GIFT_db$Code_element)],
      TRUE ~ trait
    )) %>%
    mutate(functionid = case_when(
      functionid %in% GIFT_db$Code_function ~ GIFT_db$Function[match(functionid, GIFT_db$Code_function)],
      TRUE ~ functionid
    )) %>%
    mutate(trait=factor(trait,levels=unique(GIFT_db$Element))) %>%
    mutate(functionid=factor(functionid,levels=unique(GIFT_db$Function))) %>%
    ggplot(aes(x=sample,y=trait,fill=gift)) +
        geom_tile(colour="white", linewidth=0.2)+
        scale_fill_gradientn(colours=rev(c("#d53e4f", "#f46d43", "#fdae61", "#fee08b", "#e6f598", "#abdda4", "#ddf1da")))+
        facet_grid(functionid ~ bat_species, scales="free",space="free") +
        theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1),
              strip.text.y = element_text(angle = 0)) + 
        labs(y="Traits",x="Samples",fill="GIFT")

GIFTs_functions_community %>%
    as.data.frame() %>%
    rownames_to_column(var="sample") %>%
    pivot_longer(!sample,names_to="trait",values_to="gift") %>%
    left_join(sample_metadata, by = join_by(sample == sample)) %>%
    ggplot(aes(x=trait,y=sample,fill=gift)) +
        geom_tile(colour="white", linewidth=0.2)+
        scale_fill_gradientn(colours=rev(c("#d53e4f", "#f46d43", "#fdae61", "#fee08b", "#e6f598", "#abdda4", "#ddf1da")))+
        facet_grid(bat_species ~ ., scales="free",space="free")