EPSCoR SCTC Aquatic Ecology

Create input files for ā€œbioenerg_results_analysis.Rmdā€ script

R Session Info

sessionInfo()
## R version 3.4.3 (2017-11-30)
## Platform: x86_64-apple-darwin15.6.0 (64-bit)
## Running under: macOS High Sierra 10.13.3
## 
## Matrix products: default
## BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
## LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
## 
## locale:
## [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
##  [1] compiler_3.4.3  backports_1.1.2 magrittr_1.5    rprojroot_1.3-2
##  [5] tools_3.4.3     htmltools_0.3.6 yaml_2.1.16     Rcpp_0.12.15   
##  [9] stringi_1.1.6   rmarkdown_1.8   knitr_1.19      stringr_1.2.0  
## [13] digest_0.6.15   evaluate_0.10.1

#require packages
library(googlesheets)
library(tidyverse)
library(forcats)
library(rmarkdown)
library(lubridate)
library(anytime)
suppressMessages(library(dplyr))
#detach("package:MASS", unload=TRUE) #pkg masks some dplyr functions

# Clear environment
rm(list=ls())


# a.) Temperature.csv; cols: day (DOY), temperature (C)
# b.) Predator.csv; cols: day (DOY), predator (j/g)
# c.) Prey.csv; cols: day (DOY), diet1, diet2, diet3... (energy densities)
# d.) Indigestible_Prey.csv, cols: day (DOY), diet1, diet2, diet3... (proportion indigestable)
# e.) Diet_Prop.csv; cols: day (DOY), diet1, diet2, diet3... (diet proportions)

# create folder w/ simulation name
# create sub folder named Main Inputs
# create files
# -- get daily mean temps for each water temperature file
# -- look up "predator" ED values for coho and chinook
# -- import "prey" ED values from googlesheet
# -- look up indigestability values for preycats
# -- get diet props for each year/spp/river/season


# export files to directory

# struggling to automate the process of reading in final csv temperature files from local folder.  Accomplished with manual read.csv for now

dir15 <-"/Users/bmeyer/Google Drive/Thesis/R Analysis/Temperature Data/Final Temperature Data/2015/"
dir16 <-"/Users/bmeyer/Google Drive/Thesis/R Analysis/Temperature Data/Final Temperature Data/2016/"

BC15 <- read.csv(paste0(dir15,"2015_","LBC","_H2OTemp_Final",".csv"))
RR15 <- read.csv(paste0(dir15,"2015_","LRR","_H2OTemp_Final",".csv"))
PC15 <- read.csv(paste0(dir15,"2015_","LPC","_H2OTemp_Final",".csv"))
LKR15 <- read.csv(paste0(dir15,"2015_","LKR","_H2OTemp_Final",".csv"))

BC16 <- read.csv(paste0(dir16,"2016_","LBC","_H2OTemp_Final",".csv"))
RR16 <- read.csv(paste0(dir16,"2016_","LRR","_H2OTemp_Final",".csv"))
PC16 <- read.csv(paste0(dir16,"2016_","MPC","_H2OTemp_Final",".csv"))
LKR16 <- read.csv(paste0(dir16,"2016_","LKR","_H2OTemp_Final",".csv"))

# bind all temperature files together
# binding and transformation performed seperately for 2015 and 2016 because for some reason POSIX format of DateTime column between the years is incompatible... (2/8/2018)
fnl_temps15 <- bind_rows(BC15,RR15,PC15,LKR15) %>%
transform(DateTime = mdy_hm(DateTime)) %>%
  mutate(year = year(DateTime)) %>%
  transform(Stream_Name= as.factor(Stream_Name),
            year = as.factor(year),
            Date = mdy(Date)) %>%
  select(-X,-X.1,-X.2,-X.3)

fnl_temps16 <- bind_rows(BC16,RR16,PC16,LKR16) %>%
  # something weird here eliminates 2016 datetime data
  transform(DateTime = as.POSIXct(DateTime)) %>%
  mutate(year = year(DateTime)) %>%
  transform(Stream_Name= as.factor(Stream_Name),
            year = as.factor(year),
            Date = as.Date(Date)) %>%
  select(-X)

# bind together 2015 and 2016
fnl_temps <- bind_rows(fnl_temps15,fnl_temps16) %>%
  mutate(Stream_Name_Date = paste0(Stream_Name,"_",Date))

# calculate daily mean temps
daily_mean_temps <- fnl_temps %>%
  filter(!is.na(Temp_C)) %>%
  group_by(Stream_Name,Date) %>%
  summarise(avg_temp = mean(Temp_C)) %>%
  select(Date,Stream_Name,avg_temp)  


# remove temporalry objects
rm(fnl_temps15,fnl_temps16,BC15,RR15,PC15,LKR15,BC16,RR16,PC16,LKR16,dir15,dir16)

#########################
#                       #
# B.) Diet Input        #
#                       #
#########################


# process 2015 & 2016 data simultaneously; separate as needed.
# arrange to identical structures then combine before proceeding

# 1.) Import and arrange data

# 2015 Diet Data: Import & Arrange

#create objects from overall diet data google sheets
SCTC2015 <- gs_title("2015 EPSCoR SCTC.xlsx")

SCTC2016 <- gs_title("2016_EPSCoR_Aquatic_Ecology_Database")


#read in worksheets containing diet data
diet15 <- SCTC2015 %>% 
  gs_read(ws = "2015 Diet Contents Data",col_names=TRUE) %>%
  select(Sample.ID,
         Fish_Species,
         Sample.Event,
         sample.event.num,
         River,
         Reach,
         Site,
         Sample_Date,
         Prey_Type_Used,
         PreyCategory,
         Quantity,
         Total_Prey_Dry_Mass_mg) %>%
  mutate(year = "2015") %>%
  transform(sample.event.num = as.integer(sample.event.num),
            Quantity = as.numeric(Quantity),
            Total_Prey_Dry_Mass_mg = as.numeric(Total_Prey_Dry_Mass_mg))     # columns import as character for some reason unless specified! (weird but innocuous quirk)
  

diet16 <- SCTC2016 %>% 
  gs_read(ws = "2016 Diet Contents Data",col_names=TRUE) %>%
  select(Sample.ID,
         Fish_Species,
         Sample.Event,
         sample.event.num,
         River,
         Reach,
         Site,
         Sample_Date,
         Prey_Type_Used,
         PreyCategory,
         Quantity,
         Total_Prey_Dry_Mass_mg) %>%
  mutate(year = "2016")
  
# combine 2015 and 2016 diet data
diet <- bind_rows(diet15, diet16)

# finalize structure of diet data
diet <- diet %>%  
  #rename needed columns  
  rename(sample.id = Sample.ID,
         spp = Fish_Species,
         sample.event = Sample.Event,
         event.num = sample.event.num,
         river = River,
         reach = Reach,
         site = Site,
         date = Sample_Date,
         prey = Prey_Type_Used,
         preycat = PreyCategory,
         quantity = Quantity,
         dm_mg = Total_Prey_Dry_Mass_mg) %>%
  
  #select desired columns
  select(sample.id,
         spp,
         sample.event,
         event.num,
         river,
         reach,
         site,
         date,
         year,
         prey,
         preycat,
         quantity,
         dm_mg) %>%
  
  #filter out non-diet samples and blank data
  filter(site!="DR1",
         !is.na(spp),
         !is.na(sample.event),
         !is.na(prey),
         !is.na(dm_mg),
         !is.na(quantity),
         !is.na(event.num)) %>%
  
  #transform columns to desired classes
  transform(dm_mg = as.numeric(dm_mg),
            sample.event = as.factor(sample.event),
            event.num = as.factor(event.num),
            date = mdy(date),
            spp = as.factor(spp),
            quantity = as.numeric(quantity),
            preycat = as.factor(preycat))  %>%
  mutate(season = fct_recode(event.num,         #code sampling events as seasons
                             "Early Summer"= "1", 
                             "Mid-Summer" = "2",
                             "Late Summer" = "3",
                             "Fall" = "4")) 


# create prey categorization scheme specific to bioenergetics modeling purposes
# -import from google sheet "EPSCoR_SCTC_Prey_Energy_Densities" and mutate new column to diet data
# -this sheet also contains energy density assignments, which must be manually input in "fishbioenergetics.r"
# at a later step.

Bioenergetics_ED <- gs_title("EPSCoR_SCTC_Prey_Energy_Densities")

ED <- Bioenergetics_ED %>%
  gs_read(ws = "energy_densities", col_names = TRUE) %>%
  rename(preycat = PreyCategory,
         preycat_ed = PreyCategory_ED) %>%
  transform(preycat = as.factor(preycat),
            preycat_ed = as.factor(preycat_ed))

# amend diet data with prey categories that will be used 
diet_fnl <- left_join(diet,ED,by = "preycat") %>%
  select(sample.id,prey,dm_mg,diet,preycat_ed,Energy_Density_Jg_ww)

# remove temporary objects
rm(diet15,diet16,ED)

# Import resultant data from "fish_ages_all.R" script.  The script uses methods described in Ch. 5 of Ogle 2016 ("Introductory fisheries analyses with R") to age all captured fish from a subset of fish scale samples.  Resultant csv file was copied to the google sheet referenced here.

# ID googlesheet with fish age data
fish_ages <- gs_title("all_fish_ages.csv") 

#read in worksheet containing diet data
fish_ages <- fish_ages %>% 
  gs_read(ws = "all_fish_ages.csv",col_names=TRUE) %>% 
  select (-X1) %>%
  separate(sample.event, c("reach","year","sample.event.num"), sep = "-", remove = F) %>%
  unite(river_spp, river, spp, remove = F, sep = " ") %>%
  # manually order appearance of seasons and rivers for plots
  transform(year = as.factor(year),
            river = factor(river, levels=c("Beaver Creek",
                                              'Russian River',
                                              'Ptarmigan Creek',
                                              'Kenai River')),
            season = factor(season, levels = c("Early Summer",
                                     "Mid-Summer",
                                     "Late Summer",
                                     "Fall")), 
            river_spp = as.factor(river_spp)) %>%
  mutate(river_spp_yr = paste(year,river,"\n",spp)) %>%
 # age 2 fish: this cohort is sparse and likely departing for the ocean.
  # filter(age != 2) %>%
  # mutate column for yes/no diet sampled
  mutate(diet_sample= ifelse(!is.na(sample.id), "Y", "N")) %>%
  mutate(Count = 1) %>%
  transform(Date = mdy(Date)) %>%
  mutate(doy = yday(Date))  %>%
  # filter all except coho and chinook
  filter(spp %in% c("Chinook", "Coho")) 

#eliminate duplicate rows
fish_ages <- unique(fish_ages)

# join fish ages date with diet data
diet <- left_join(diet_fnl, fish_ages, by = "sample.id" )


How many fish have diet samples, but no age designation?



# How many fish have diet samples, but no age designation?
diet_no_age <- diet %>%
  filter(is.na(age)) %>%
  distinct(sample.id)
diet_no_age <- nrow(diet_no_age)

#exclude these individuals
diet <- diet %>%
  filter(!is.na(age))

There are 17 fish with diet samples but no age assigned. These 17 fish must have both two conditions true:

  1. Fish was not part of a river/year/spp where an age-length key could be developed.

  2. Fish did not have a read-able scale.

We will exclude these 17 fish from analyses… for now, because we are running simulations seperately by age year/river/spp/age. Fish must have an age.



#create sum of pooled prey DM for each prey category by fish species and sample event 
dm_sum_by_event <- diet %>%
  group_by(year,river,spp,preycat_ed,season,age) %>%
  summarise(sum(dm_mg)) %>%
  rename(dm_sum =`sum(dm_mg)`) %>%
  spread(preycat_ed,dm_sum) %>%
  rowwise() %>%
  mutate(dm_tot = sum(FishEggs,    # create column for summed dry mass of all prey categories
                      InvertAquatic_AqOrigin,
                      InvertTerrestrial,
                      InvertTerrestrial_AqOrigin,
                      InvertUnknown,
                      SalmonEggs, 
                      na.rm = TRUE)) %>%
  mutate(FishEggs = FishEggs/dm_tot,
         # change prey quantities to relative proportions by category
         InvertAquatic_AqOrigin = InvertAquatic_AqOrigin/dm_tot,  
         InvertTerrestrial = InvertTerrestrial/dm_tot,
         InvertTerrestrial_AqOrigin = InvertTerrestrial_AqOrigin/dm_tot,
         InvertUnknown = InvertUnknown/dm_tot,
         SalmonEggs = SalmonEggs/dm_tot) %>%
  transform(year = as.factor(year)) %>%
  select(-X.NA.) %>%
  rename(Stream_Name = river)


d.) Define temporal extents of proposed simulations
# Define temporal extents of proposed simulations

# NOTE 1/22/18: this code also exists as a script at "/Users/bmeyer/Google Drive/Thesis/R Analysis/Thesis Analyses R Project/Overall_scripts_2015_2016/sampling_periods.R".  Attempted to just source("\path") this script in to the markdown document but, 'source' function prevents knitting through markdown for some reason.  

############
#
# 2015
#
###########

# Verify that sheet is present, create object of sheet with all tabs
SCTC2015 <- gs_title("2015 EPSCoR SCTC.xlsx")

#read in specific worksheet containing fishing data
effort2015 <- SCTC2015 %>% 
  gs_read(ws = "B Fishing Data",col_names=TRUE, skip=2) %>%
  #rename needed columns  
  rename(site.id=Site_ID,
         sample.event=Sample_Event) %>%
  
  #select desired columns
  select(site.id,River,sample.event,sample.event.num,deploy_dt,collect_dt) %>%
  
  #filter out blanks
  filter(!is.na(sample.event)) %>%
  
  # transform columns to desired classes
  transform(site.id=as.factor(site.id),
            sample.event=as.factor(sample.event),
            sample.event.num=as.factor(sample.event.num)) 


###################
#
# 2016
#
###################

# Verify that sheet is present, create object of sheet with all tabs
SCTC2016 <- gs_title("2016_EPSCoR_Aquatic_Ecology_Database")

#read in specific worksheet containing fishing data
effort2016 <- SCTC2016 %>% 
  gs_read(ws = "B Fishing Data",col_names=TRUE, skip=2) %>%
  
  #rename needed columns  
  rename(site.id=Site_ID,
         sample.event=Sample_Event) %>%
  
  #select desired columns
  select(site.id,River,sample.event,sample.event.num,deploy_dt,collect_dt) %>%
  
  #filter our blanks
  filter(!is.na(sample.event)) %>%
  
  # transform columns to desired classes
  transform(site.id=as.factor(site.id),
            sample.event=as.factor(sample.event),
            sample.event.num=as.factor(sample.event.num)) 


# bind 2015 & 2016 data; format datetimes
effort <- bind_rows(effort2015,effort2016) %>%
  transform(collect_dt = anytime(collect_dt),
            deploy_dt = anytime(deploy_dt)) %>%
  mutate(year = year(collect_dt)) 



# Define Temporal Extents of proposed simulations 

# "Simulation" temporal extent
# Time period from first date of each season to first date of following season

# prepare data to tibble form
sim_extents <- effort %>% 
  select(-site.id) %>%
  group_by(River, year, sample.event.num) %>% 
  nest() %>% 
  mutate(season.start = map_dbl(data, ~min(.$deploy_dt)),
         season.end = map_dbl(data, ~min(.$deploy_dt))
         ) %>%
  transform(season.start = anytime(season.start),
            season.end = anytime(season.end)) %>%
  arrange(River,year,sample.event.num)

# prepare data such that end of one season is beginning of next
t <- sim_extents %>%
  mutate(season.end_x = lead(season.end)) %>%
  select(-season.end) %>%
  arrange(River,year,sample.event.num)

# prepare data such that final season of each year has duration of 30 days.
# 2015 had 3 seasons, 2016 had 4 seasons.

t_end15 <- t %>%
  filter(sample.event.num == 3,
         year == 2015) %>%
  mutate(season.end = season.start + days(30)) %>%
  select(-season.end_x)

t_end16 <- t %>%
  filter(sample.event.num == 4,
         year == 2016) %>%
  mutate(season.end = season.start + days(30)) %>%
  select(-season.end_x)

t_end15_1 <- t %>%
  filter(sample.event.num != 3,
         year != 2016) %>%
  rename(season.end = season.end_x)

t_end16_1 <- t %>%
  filter(sample.event.num != 4,
         year != 2015) %>%
  rename(season.end = season.end_x)

# final version of simulation extents
sim_extents <- bind_rows(t_end15_1,t_end15,t_end16_1,t_end16) %>%
  rename(Stream_Name = River,
         sim.start = season.start,
         sim.end = season.end) %>%
  transform(year = as.factor(year)) %>%
  mutate(season = fct_recode(as.factor(sample.event.num),         #code sampling events as seasons
                             "Early Summer"="1", 
                             "Mid-Summer" = "2",
                             "Late Summer" ="3",
                             "Fall" = "4")) %>%
  select(-data)

# remove temporary objects
rm(t,t_end15,t_end15_1,t_end16,t_end16_1,effort2015,effort2016)

# make plot that visualizes extent of each simulation period faceted by year and river

# simulation extents all run 30 days forward from 1st sampling date in season

sim_extents_mod <- sim_extents %>%
  mutate(sim.start.doy = yday(sim.start),
         sim.end.doy = yday(sim.end),
         year = year(sim.start))


theme_bm <- theme(axis.text.x = element_text(size=18),
                  axis.text.y = element_text(size=18),                       # x axis text
                  axis.title.x = element_text(size=18, face = "bold"),          # x axis title
                  axis.title.y = element_text(size=18, face = "bold"),
                  strip.text.x = element_text(size = 16, face = "bold"),
                  legend.text = element_text(size = 16)) 

# test plot
s <- ggplot(sim_extents_mod, aes(x=sim.start.doy, xend = sim.end.doy, 
                            y=as.factor(year), yend=as.factor(year), color = season)) +
  theme_bw() +
  ggtitle("Bioenergetics Simulation Periods") +
  geom_segment(aes(color = season), size = 10) + 
  facet_wrap(~Stream_Name) +
  xlab("Day of Year") +
  ylab("Year") +
  theme(plot.title = element_text(size= 24, face = "bold", hjust = 0.5)) +
  theme(legend.title=element_text(size=24)) +
  guides(color = guide_legend(override.aes = list(size=8))) +
  scale_color_manual(name="Season",
                     breaks = c("Early Summer",
                                "Mid-Summer",
                                "Late Summer",
                                "Fall"),
                     values=c("red", "purple", "turquoise", "green")) +
  
  
  #
  theme_bm

s


# match temporal extent of simulated diet proportion data to simulation date if it exists. 
diet_prop_seasons <- left_join(dm_sum_by_event,sim_extents,by=c("Stream_Name","season","year")) %>%
  mutate(days = round(sim.end-sim.start))

# extend diet props down length of season
sim_diet_days <- diet_prop_seasons[rep(seq_len(nrow(diet_prop_seasons)),diet_prop_seasons[,"days"]), ]

# add a row # ("SimDay") per row within each desired sim group, 
sim_diet_days <- sim_diet_days %>%
  mutate(sim_name = paste0(year,"_",
                           season,"_",
                           Stream_Name,"_",
                           spp,"_",
                           "Age","_",
                           age)) %>%
  group_by(sim_name) %>%
  mutate(SimDay = row_number()) %>%
  mutate(Date = sim.start + days(SimDay)) %>%
  transform(Date = date(Date))

# join daily mean temperatures with diet proportions
sim_diet_days <- left_join(sim_diet_days,daily_mean_temps,by=c("Date","Stream_Name"))

 # arrange and rename columns to format identical as in "InputFileTemplate" for bioenergetics modeling

sim_diet_days <- sim_diet_days %>%
  rename(Diet1 = FishEggs,
         Diet2 = InvertAquatic_AqOrigin,
         Diet3 = InvertTerrestrial,
         Diet4 = InvertTerrestrial_AqOrigin,
         Diet5 = InvertUnknown,
         Diet6 = SalmonEggs,
         Temp = avg_temp) %>%
  # add in blank columns 7-10 to match InputFileTemplate format
  mutate(Diet7 = 0,
         Diet8 = 0,
         Diet9 = 0,
         Diet10 = 0) %>%
  # select desired columns  
  select(Date,SimDay,Temp,
         contains("Diet"),
         sim_name,spp) %>%
  # ensure that list of dataframes and list of dataframe names match up order in next step
  arrange(sim_name) %>%
  # round decimals to two digits
  mutate_if(is.numeric, funs(round(., 1))) %>%
  # filter out simulation days with no temperature data; trim lengths of sims to days w/ sims
  filter(!is.na(Temp)) 
  
#replace all NA's with 0's
sim_diet_days[is.na(sim_diet_days)] <- 0

# eliminate simulations where diet inputs are all zeros
# a.) create dataframe that conatins sim names with zero diet content
zero_sims <- sim_diet_days %>%
  select(-spp) %>%
  group_by(sim_name) %>% 
  summarise_each(funs(sum)) %>%
  # sum across columns with diet proportions
  mutate(diet_prop_sum = rowSums(.[3:12])) %>%
  select(sim_name, diet_prop_sum) %>%
  # filter to create dataframe of simulations with zero diet content
  filter(diet_prop_sum == 0)

# export names of simulations with zero diet mass to google sheet for later reference

# code below hastagged out b/c there are already no samples included w/ zero diet mass

## remove any existing googlesheet resulting from previous runs of this script
#zero_sims_gs <- gs_title("zero_diet_mass_sims")
#gs_delete(zero_sims_gs)
## write new sheet with data
#gs_new("zero_diet_mass_sims", input = zero_sims)

# b.) use above table to remove simulatins with zero diet content
#sim_diet_days <- anti_join(sim_diet_days,zero_sims)

# arrange columns in desired order
sim_diet_days <- sim_diet_days %>%
  select(Date,SimDay,Temp,Diet1,Diet2,Diet3,Diet4,Diet5,Diet6,Diet7,Diet8,Diet9,Diet10,sim_name,spp)

# create table connecting SimDay, Sim_Name, and Date information 
sim_dates_x <- sim_diet_days %>%
  select(sim_name,SimDay,Date)

# export table connecting Sim.Day, Sim_Name, and Date information for later use in analysis
sim_dates <- gs_title("sim_dates")
gs_delete(sim_dates)
gs_new("sim_dates", ws_title ="Sheet1",  input = sim_dates_x)

# remove Date column from sim_diet_days
sim_diet_days <- sim_diet_days %>%
  select(-Date)

write.csv(sim_dates_x, file = "tmp.csv")

# choose data for subset of simulations selected in script "bioenerg_dat_input_selection.Rmd"

# a.) import sheet with list of simulations subsetted (output table from "bioenerg_dat_input_selection.Rmd")
sim_size_inputs_list <- gs_title("sim_size_inputs") 
sim_size_inputs_list <- sim_size_inputs_list %>%
  gs_read(ws = "lw_data") %>%
  select(sim_name)

# b.) Filter table of diet proportion data to include only chosen subset of simulations
sim_diet_days <- semi_join(sim_diet_days,sim_size_inputs_list) 
# How many simulations included?
n_sims <- nrow(sim_size_inputs_list)

# restructure table to prep for txt format export

# acquire string of column names for desired final table
colnames_df <- sim_diet_days %>%
  ungroup() %>%
  select(-spp,-sim_name)
sim_col_names <- toString(names(colnames_df))

# remove commas from character string
sim_col_names <- gsub(",", "", sim_col_names, fixed = TRUE)

# unite content of data columns in to text string
sim_diet_days <- sim_diet_days %>%
  # name of new column is "foo", later replaced with string of all col names
  unite("foo",SimDay,Temp,    
        contains("Diet"),
        sep = " ")

# assign column names 
colnames(sim_diet_days) <- c(sim_col_names,"sim_names","spp")

#recreate grouping variable
sim_diet_days <- sim_diet_days %>%
  group_by(sim_names)

# create individual dataframes for each species
sim_diet_days_coho <- sim_diet_days %>%
  filter(spp == "Coho") %>%
  select(-spp)

sim_diet_days_chnk <- sim_diet_days %>%
  filter(spp == "Chinook") %>%
  select(-spp)

# split up all data in to lists of individual simulations by year, river, species, age, and season
sim_list_coho <- split.data.frame(sim_diet_days_coho, sim_diet_days_coho$sim_names)
sim_list_chnk <- split.data.frame(sim_diet_days_chnk, sim_diet_days_chnk$sim_names)

# remove column containing name of simulation from all objects in list
sim_list_coho <- lapply(sim_list_coho, function(x) x[!(names(x) %in% c("sim_names"))])
sim_list_chnk <- lapply(sim_list_chnk, function(x) x[!(names(x) %in% c("sim_names"))])

Note: for some reason txt files are not exporting to the proper sub-folder; moved manually after export from here… 2/18/18


# get names of all simulations in a list
sim_names_coho <- sim_diet_days_coho %>%
  select(sim_names) %>%
  distinct()
sim_names_coho <- as.list(sim_names_coho)

# set working directory to destination for data
setwd("/Users/bmeyer/Google Drive/Thesis/R Analysis/Bioenergetics/coho_biol_input")

# clear out working directory folder if it already has existing files
do.call(file.remove, list(list.files("/Users/bmeyer/Google Drive/Thesis/R Analysis/Bioenergetics/coho_biol_input", full.names = TRUE)))

# write dataframes as individual txt files to working directory
lapply(names(sim_list_coho),
       function(x, sim_list_coho) 
         write.table(sim_list_coho[[x]],
                     paste(x, ".txt", sep = ""),
                     col.names=TRUE, 
                     row.names=FALSE,
                     sep="\t",
                     quote=FALSE),sim_list_coho)

# individual simulations now saved as txt files in working directory.
# these contain diet proportions for each SimDay and the mean temperature
# at the lower watershed site.

# get names of all simulations in a list
sim_names_chnk <- sim_diet_days_chnk %>%
  select(sim_names) %>%
  distinct()
sim_names_chnk <- as.list(sim_names_chnk)

# set working directory to destination for data
setwd("/Users/bmeyer/Google Drive/Thesis/R Analysis/Bioenergetics/chnk_biol_input")

# clear out working directory folder if it already has existing files
do.call(file.remove, list(list.files("/Users/bmeyer/Google Drive/Thesis/R Analysis/Bioenergetics/chnk_biol_input", full.names = TRUE)))

# write dataframes as individual txt files to working directory
lapply(names(sim_list_chnk),
       function(x, sim_list_chnk) 
         write.table(sim_list_chnk[[x]],
                     paste(x, ".txt", sep = ""),
                     col.names=TRUE, 
                     row.names=FALSE,
                     sep="\t",
                     quote=FALSE),sim_list_chnk)

# individual simulations now saved as txt files in working directory.
# these contain diet proportions for each SimDay and the mean temperature
# at the lower watershed site.

Final outcome: diet proportions at scale of year/river/spp/age by day w/ water temp, stored in local directory