Last updated: 2022-12-29

Checks: 6 1

Knit directory: freezing_cycles/

This reproducible R Markdown analysis was created with workflowr (version 1.7.0). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


The R Markdown is untracked by Git. To know which version of the R Markdown file created these results, you’ll want to first commit it to the Git repo. If you’re still working on the analysis, you can ignore this warning. When you’re finished, you can run wflow_publish to commit the R Markdown file and build the HTML.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20220415) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version ed0e131. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    analysis/site_libs/

Untracked files:
    Untracked:  analysis/2.freezing_vs_environment.Rmd
    Untracked:  data/tree.nwk

Unstaged changes:
    Deleted:    .DS_Store
    Modified:   analysis/0.data.Rmd
    Modified:   analysis/1.freezing_cycles_tolerance.Rmd
    Deleted:    analysis/2.long_freezing_vs_cycles.Rmd
    Deleted:    analysis/3.freezing_vs_environment.Rmd
    Modified:   analysis/index.Rmd
    Modified:   code/model.txt
    Deleted:    data/.DS_Store
    Modified:   data/data_freezing.xlsx
    Modified:   data/mixedmonths_data.txt
    Deleted:    data/tree.nex
    Modified:   freezing_tardigrades.Rproj
    Deleted:    output/M_vs_plong_plot.svg
    Modified:   output/means_cycles.txt
    Modified:   output/mod.env.rds
    Modified:   output/model_fit.env.pdf
    Deleted:    output/plot_mod_fitenv.pdf
    Deleted:    output/tree_Cycles.svg

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


There are no past versions. Publish this analysis with wflow_publish() to start tracking its development.


Load sampling coordinates of used species

points = data.frame(read_xlsx("./data/data_freezing.xlsx", sheet = "species_data"))[,1:3]

Get climatic data for species sampling locations

# This script extracts how many months have the minimum temperature below zero and the maximum temperature above zero (from Bioclim rasters) and save it in a table. 
# As the raw climatic rasters are very heavy (~ 10Gb), this code is not run, but only shown here.
# The tmin and tmax data rasters can be downloaded at: https://www.worldclim.org/data/monthlywth.html


tmin.list = list.files(path="./data/tmin", 
                           pattern =".tif", full.names=TRUE)
tmin.stack = raster::stack(x=tmin.list)
tmins = data.frame(raster::extract(tmin.stack, points[,3:2]))
tmins = cbind(points$species_code, tmins)
tmins = gather(tmins, "month", "temp_min", 2:ncol(tmins))
colnames(tmins)[1] ="species"
tmins$month = substr(tmins$month,start=17, stop = 23)


tmax.list = list.files(path="./data/tmax", 
                       pattern =".tif", full.names=TRUE)
tmax.stack = raster::stack(tmax.list)
tmax = data.frame(raster::extract(tmax.stack, points[,3:2]))
tmax = cbind(points$species_code, tmax)
tmax = gather(tmax, "month", "temp_max", 2:ncol(tmax))
colnames(tmax)[1] ="species"
tmax$month = substr(tmax$month,start=17, stop = 23)


temp_all = distinct(merge(tmins, tmax, by=c("species","month"))) 


  low = (temp_all$temp_min<0) * (temp_all$temp_max<0) # not really necessary
  mixed = (temp_all$temp_min<0) * (temp_all$temp_max>0)
  high = (temp_all$temp_min>0) * (temp_all$temp_max>0)

month_class = rep("low", nrow(temp_all))
month_class[as.logical(mixed)] = "mixed"
month_class[as.logical(high)] = "high"
  
temp_all$month_class = month_class

sum_table = data.frame(table(temp_all$species, temp_all$month_class))
colnames(sum_table) = c("species_code", "type", "count")
sum_table = sum_table %>% filter(type == "mixed") %>% mutate(prop_mixed = count/108)

write.table(sum_table, "./data/mixedmonths_data.txt")
bioclims_extracted = read.table("./data/mixedmonths_data.txt", header=T)

Merge climatic data with freezing cycles tolerance data

data_merged = merge(read.table("./output/means_cycles.txt", header=T),bioclims_extracted)
data_merged$scaled_M = as.numeric(scale(data_merged$M))

Load phylogenetic tree

tree = read.tree("./data/tree.nwk")
tree = root(tree,"Milnesium_variefidum")
tree = chronos(tree)
tree = drop.tip(tree, tip = tree$tip.label[!(tree$tip.label %in% data_merged$species)])
class(tree) = "phylo"

data_merged = data_merged[data_merged$species %in% tree$tip.label,]

Run JAGS model

phylo.matrix = vcv.phylo(tree)
inv.phylo.matrix = solve(phylo.matrix)

data_merged = data_merged[match(rownames(inv.phylo.matrix),data_merged$species),]

data.jags = list(M = data_merged$scaled_M,
                 mixprop = as.numeric(scale(data_merged$prop_mixed)),
                 inv.phylo.matix = inv.phylo.matrix,
                 nsp = nrow(inv.phylo.matrix),
                 zeros = rep(0, nrow(inv.phylo.matrix)))

# The model includes some truncated priors. As it is not possible to do it by specifying the modell as function in R, the moded is loaded as txt file.

parameters.jags = c("alpha","beta","sigma.phylo","sigma.res","marginalR2","conditionalR2","residualR2","phylogeneticR2")


ifelse("mod.env.rds" %in% list.files("./output"),{fit.env = readRDS("./output/mod.env.rds")},{

  fit.env = jags(data = data.jags,
               parameters.to.save = parameters.jags,
               model.file = "./code/model.txt",
               n.chains = 3, n.iter = 10000000)
write_rds(fit.env, file="./output/mod.env.rds")
  
})

# Make diagnostic plots (not showed but saved as pdf)
ggmcmc(ggs(as.mcmc(fit.env)), file="./output/model_fit.env.pdf", param_page=2)

Download model file here:

Download mod.env.rds

Download diagnostic plots here:

Download model_fit.env.pdf

Calculate p.values and show model estimates

chains = data.frame(do.call(rbind,as.mcmc(fit.env)))

p_dir = p_direction(chains)
p_vals = pd_to_p(p_dir$pd)
p_vals[3:9] = rep(NA,7)
names(p_vals) = p_dir$Parameter

fit.env$BUGSoutput$summary %>% cbind(p_vals) %>% round(4) %>%datatable(class = 'cell-border stripe')

The beta paramenter represent the effect of the proportion on “mixed” months on the resistance to freeze-thaw cycles. It is positive and significant, so the more the mixed months there are, the more the tardigrades are resistent.


sessionInfo()
R version 4.2.1 (2022-06-23 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)

Matrix products: default

locale:
[1] LC_COLLATE=English_United Kingdom.utf8 
[2] LC_CTYPE=English_United Kingdom.utf8   
[3] LC_MONETARY=English_United Kingdom.utf8
[4] LC_NUMERIC=C                           
[5] LC_TIME=English_United Kingdom.utf8    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] xfun_0.34         ggmcmc_1.5.1.1    DT_0.26           patchwork_1.1.2  
 [5] R2jags_0.7-1      rjags_4-13        coda_0.19-4       bayestestR_0.13.0
 [9] ape_5.6-2         raster_3.6-3      rgdal_1.6-2       sp_1.5-1         
[13] readxl_1.4.1      forcats_0.5.2     stringr_1.4.1     dplyr_1.0.10     
[17] purrr_0.3.5       readr_2.1.3       tidyr_1.2.1       tibble_3.1.8     
[21] ggplot2_3.4.0     tidyverse_1.3.2  

loaded via a namespace (and not attached):
 [1] nlme_3.1-160        fs_1.5.2            lubridate_1.9.0    
 [4] RColorBrewer_1.1-3  insight_0.18.7      httr_1.4.4         
 [7] rprojroot_2.0.3     tools_4.2.1         backports_1.4.1    
[10] bslib_0.4.1         utf8_1.2.2          R6_2.5.1           
[13] R2WinBUGS_2.1-21    DBI_1.1.3           colorspace_2.0-3   
[16] withr_2.5.0         GGally_2.1.2        tidyselect_1.2.0   
[19] compiler_4.2.1      git2r_0.30.1        cli_3.4.1          
[22] rvest_1.0.3         xml2_1.3.3          labeling_0.4.2     
[25] sass_0.4.2          scales_1.2.1        digest_0.6.30      
[28] rmarkdown_2.18      pkgconfig_2.0.3     htmltools_0.5.3    
[31] dbplyr_2.2.1        fastmap_1.1.0       htmlwidgets_1.5.4  
[34] rlang_1.0.6         rstudioapi_0.14     farver_2.1.1       
[37] jquerylib_0.1.4     generics_0.1.3      jsonlite_1.8.3     
[40] crosstalk_1.2.0     googlesheets4_1.0.1 magrittr_2.0.3     
[43] Rcpp_1.0.9          munsell_0.5.0       fansi_1.0.3        
[46] abind_1.4-5         lifecycle_1.0.3     terra_1.6-17       
[49] stringi_1.7.8       yaml_2.3.6          plyr_1.8.8         
[52] grid_4.2.1          parallel_4.2.1      promises_1.2.0.1   
[55] crayon_1.5.2        lattice_0.20-45     haven_2.5.1        
[58] hms_1.1.2           knitr_1.41          pillar_1.8.1       
[61] boot_1.3-28         codetools_0.2-18    reprex_2.0.2       
[64] glue_1.6.2          evaluate_0.18       modelr_0.1.10      
[67] vctrs_0.5.0         tzdb_0.3.0          httpuv_1.6.6       
[70] cellranger_1.1.0    gtable_0.3.1        reshape_0.8.9      
[73] assertthat_0.2.1    datawizard_0.6.4    cachem_1.0.6       
[76] mime_0.12           broom_1.0.1         later_1.3.0        
[79] googledrive_2.0.0   gargle_1.2.1        workflowr_1.7.0    
[82] timechange_0.1.1    ellipsis_0.3.2