-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathESPRESSO.Analysis.Rmd
5653 lines (4880 loc) · 290 KB
/
ESPRESSO.Analysis.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Analysis of ESPRESSO data (Stable 20.01.2016)"
author: "Your Name Goes Here"
output: rmarkdown::tufte_handout
---
# Introduction
*Describe your hypothesis and experimental details here.*
```{r setVariables, echo = FALSE}
h <- 4 # Duration of experiment, IN HOURS. Change this if you just want to analyse, say, the first 3 hours.
bs <- 300 # Bin size of combined density raster plot, in seconds. Anywhere between 5 min (300s) and 10 min (600s) seems to be good.
bw <- 600 # Bin-sizes of time-course in seconds (s). Change here to change the bin size. (600s = 10 min)
file.path <- c("/Users/josesho/Desktop/scratch/ESPRESSO/fromAndersJan2016")
# Local file directory path name where data files are stored.
time.stamp <- format(Sys.time(), "%d-%m-%Y_%H.%M.%S_hrs")
setwd(file.path)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE,
fig.path = paste(file.path, "/Figures_", time.stamp, "/", sep = "") )
feedlog.path <- paste(file.path, "/feedlog", sep = "")
metadata.path <- paste(file.path, "/metadata", sep = "")
output.path <- paste(file.path, "/output_", time.stamp, sep = "")
dir.create(output.path) # Creates an output folder in home directory.
# Sets options for Knitr package. You should not have to edit the two lines above.
```
```{r installPackages, eval = FALSE}
# For data manipulation
install.packages("dplyr")
install.packages("tidyr")
install.packages("data.table")
install.packages("lazyeval")
# For date-time manipulation
install.packages("lubridate")
# For running Dunn's Test
install.packages("dunn.test")
# For calculation of Hedges' g
install.packages("metafor")
# To calculate 95% CIs by bootstrapping
install.packages("boot")
# For nice graphs.
install.packages("grid")
install.packages("gtable")
install.packages("ggplot2")
install.packages("gridExtra")
install.packages("cowplot")
install.packages("Rmisc")
devtools::install_github("eclarke/ggbeeswarm")
# To grab data from Google Sheets
install.packages("mosaic")
# In case I need to standardise colours across different graphs
install.packages("RColorBrewer")
# In case I want pretty tables.
install.packages("xtable")
```
```{r LoadLibraries}
# For running Dunn's Test
library("dunn.test")
# For calculation of Hedges' g
library("metafor")
# To calculate 95% CIs by bootstrapping
# library("boot")
# For nice graphs.
library("grid")
library("gtable")
library("ggplot2")
library("gridExtra")
library("cowplot")
library("Rmisc")
library("ggbeeswarm")
library("scales")
# To grab data from Google Sheets
library("mosaic")
# In case I need to standardise colours across different graphs
library("RColorBrewer")
# In case I want pretty tables.
library("xtable")
options(xtable.comment = FALSE)
options(xtable.booktabs = TRUE)
# For data manipulation
library("dplyr") # Load AFTER plyr!!
library("tidyr")
library("data.table")
library("lazyeval")
# For date-time maniuplation
library("lubridate")
# load("~/baseLoad.RData")
```
```{r defFunctions}
# See http://stackoverflow.com/questions/12539348/ggplot-separate-legend-and-plot
get_legend<-function(myggplot){
tmp <- ggplot_gtable(ggplot_build(myggplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)
}
# Code from https://zachexchange.wordpress.com/2013/08/03/binning-observations-r-or-creating-a-time-series-of-counts/
get.bin.counts = function(x, name.x = "x", start.pt, end.pt, bin.width) {
br.pts = seq(start.pt, end.pt, bin.width)
x = x[(x >= start.pt)&(x <= end.pt)]
counts = hist(x, breaks = br.pts, plot = FALSE)$counts
dfm = data.frame(br.pts[-length(br.pts)], counts)
names(dfm) = c(name.x, "freq")
return(dfm)
}
pi.calc <- function(v) {
v <- as.numeric(v)
sum <- sum(v)
diff <- v[2] - v[1]
pi <- diff/sum
return(pi)
}
mean_se_paste <- function(v) {
v <- as.numeric(v)
a <- mean_se(v, mult = 1.96)
aa <- unlist(unname(a))
return(paste(aa, collapse = ","))
}
average <- function(data, i) {
a <- data[i]
return(mean(a))}
# To use:
# x <- boot(z, average, R = 200)
# xx <- boot.ci(x)
# Remove whitespace, from http://stackoverflow.com/questions/2261079/how-to-trim-leading-and-trailing-whitespace-in-r
# trim <- function (x) gsub("^\\s+|\\s+$", "", x)
```
# Results
```{r LoadData}
# Read all metadata files into 1 list.
metadata.list <- lapply(list.files(path = metadata.path, full.names = T), FUN = read.csv)
names(metadata.list) <- list.files(path = metadata.path)
# Check if need to use csv2
for (i in 1:length(metadata.list)) {
if (ncol(metadata.list[[i]]) == 1 ) {
metadata.list <- lapply(list.files(path = metadata.path, full.names = T), FUN = read.csv2)
names(metadata.list) <- list.files(path = metadata.path)
}
}
# Read all feedlogs into 1 list.
feedlog.list <- lapply(list.files(path = feedlog.path, full.names = T), FUN = read.csv)
names(feedlog.list) <- list.files(path = feedlog.path)
# Check if need to use csv2
for (i in 1:length(feedlog.list)) {
if (ncol(feedlog.list[[i]]) == 1 ) {
feedlog.list <- lapply(list.files(path = feedlog.path, full.names = T), FUN = read.csv2)
names(feedlog.list) <- list.files(path = feedlog.path)
}
}
```
```{r MetadataProcessAndCombine}
for (i in 1:length(metadata.list)) {
# Rename Chamber.number column as ID.
if ( "Chamber.number" %in% colnames(metadata.list[[i]]) ) {
metadata.list[[i]][, "ID"] <- metadata.list[[i]][, "Chamber.number"]
metadata.list[[i]][, "Chamber.number"] <- NULL
}
# Then rename ID as FlyID to be consistent with feedlog.all
# Add column "original.ID.metadata"
metadata.list[[i]][, "FlyID"] <- metadata.list[[i]][, "original.FlyID.metadata"] <- metadata.list[[i]][, "ID"]
# So as not to confuse ourselves, also note that the FlyIDs in the feedlog differ from that in the metadata by 1.
metadata.list[[i]][, "original.FlyID.feedlog"] <- metadata.list[[i]][, "ID"] - 1
metadata.list[[i]][, "ID"] <- NULL
# Add column with originating metadata file
metadata.list[[i]][,"original.metadata.file"] <- rep(names(metadata.list)[i],
length(metadata.list[[i]][, "FlyID"] ))
# Add column with feedlog file
metadata.list[[i]][,"original.feedlog.file"] <- rep(names(feedlog.list)[i],
length(metadata.list[[i]][, "FlyID"] ))
# Then add previous number of flies from last metadata to avoid overlap of FlyIDs.
if (i > 1) {
metadata.list[[i]][, "FlyID"] <-
metadata.list[[i]][, "FlyID"] +
range(metadata.list[[i - 1]][, "FlyID"])[2]
}
# # Determine how many feeds each fly in the metadata made.
# metadata.list[[i]][, "total.feed.counts"] <- rep("", length(metadata.list[[i]][, "FlyID"] ))
# for ( row in 1:nrow(metadata.list[[i]]) ) {
# temp.df <-
# feedlog.list[[i]] %>%
# group_by(FlyID) %>%
# summarise( total.feed.count = length(Volume.mm3) )
# }
#
# Order the columns properly.
metadata.list[[i]] <- as.data.table( metadata.list[[i]] )
setcolorder(metadata.list[[i]], colnames(metadata.list[[1]]))
metadata.list[[i]] <- data.frame(metadata.list[[i]])
}
# Combine the metadata
metadata.all <- do.call('rbind', metadata.list)
rownames(metadata.all) <- NULL
# Change all columns (except `original.metadata.file`) to uppercase, to mitigate capitilization errors.
for ( c in colnames(metadata.all)[!colnames(metadata.all) %in% c("original.metadata.file", "original.feedlog.file")] ) {
metadata.all[, c] <- as.factor(toupper(metadata.all[, c]))
}
# Write to file.
write.csv(metadata.all, file = paste(output.path, "/metadata.all.csv", sep = ""), row.names = FALSE)
```
```{r MakeIdConversionList}
id.conversion <- list()
for (rownum in 1:nrow(metadata.all)) {
id.conversion[[ as.character(metadata.all[rownum, "FlyID"]) ]] <-
data.frame( metadata = as.character( metadata.all[rownum, "original.FlyID.metadata"] ),
feedlog = as.character( metadata.all[rownum, "original.FlyID.feedlog"] ),
metadata.file = as.character( metadata.all[rownum, "original.metadata.file"] ),
feedlog.file = as.character( metadata.all[rownum, "original.feedlog.file"] ))
}
```
```{r FeedlogCalculateRelativeTimeAndCombine}
for (i in 1:length(feedlog.list)) {
# change name of evaporation column, to save trouble later
if ("Evap.mm3.s" %in% colnames(feedlog.list[[i]]) ) {
feedlog.list[[i]][, "Evap.mm3.per.sec"] <- feedlog.list[[i]][, "Evap.mm3.s"]
feedlog.list[[i]][, "Evap.mm3.s"] <- NULL
}
# New column for originating feedlog and metdata filename
feedlog.list[[i]][,"original.metadata.file"] <- rep(names(metadata.list)[i],
length(feedlog.list[[i]][, "FlyID"] ))
feedlog.list[[i]][,"original.feedlog.file"] <- rep(names(feedlog.list)[i],
length(feedlog.list[[i]][, "FlyID"] ))
# Handle StartTime
feedlog.list[[i]][, "StartTime"] <- as.character(feedlog.list[[i]][, "StartTime"])
feedlog.list[[i]][, "StartTime"] <- parse_date_time(feedlog.list[[i]][, "StartTime"], "%d/%m/%Y %H:%M:%S", tz = "")
# New column for original FlyID
feedlog.list[[i]][, "original.FlyID.feedlog"] <- feedlog.list[[i]][, "FlyID"]
feedlog.list[[i]][, "original.FlyID.metadata"] <- feedlog.list[[i]][, "FlyID"] + 1
# Add 1 to each FlyID, to match up with metadata.
feedlog.list[[i]][, "FlyID"] <- feedlog.list[[i]][, "FlyID"] + 1
# Then add previous number of flies from last metadata file to avoid overlap of FlyIDs.
if (i > 1) {
feedlog.list[[i]][, "FlyID"] <-
feedlog.list[[i]][, "FlyID"] +
range(metadata.list[[i - 1]][, "FlyID"])[2] # NOTE THAT THE RANGE FROM metadata.list IS USED HERE INSTEAD.
}
# Check if "Valid", "RelativeTime.s", and "ExperimentState" are columns.
new.cols <- c("Valid", "RelativeTime.s", "ExperimentState")
for (c in new.cols) {
if ( !c %in% colnames(feedlog.list[[i]]) ) {
feedlog.list[[i]][, c] <- rep(NA , nrow(feedlog.list[[i]]))
}
}
if ( is.na(feedlog.list[[i]][1, "RelativeTime.s"]) ) {
# Read in AssayStartTimeAbsolute from the filename
filename <- list.files(feedlog.path)[i]
s <- unlist(strsplit(filename, "\\_")) # The '\' in front of the separater ensure a regular expression is used.
AssayStartTimeAbsolute <- paste(s[2], s[3], sep = " ")
AssayStartTimeAbsolute <- parse_date_time(AssayStartTimeAbsolute, "%Y-%m-%d %H-%M-%S", tz = "")
if (is.na(AssayStartTimeAbsolute)) {
stop( paste("Check the filename for the feedlog file ", names(feedlog.list)[i],
" Please make sure that the date is in YYYY-mm-dd format,",
" and that the time is in hh-mm-ss format,",
" and BOTH date and time MUST be flanked by underscores ' _ '.", sep = "") )
}
# time.vector <- rep(AssayStartTimeAbsolute, nrow(feedlog.list[[i]]))
# Obtain FeedStartTimeRelative (relative to Assay Start Time, which is t = 0.)
feedlog.list[[i]][, "RelativeTime.s"] <- as.numeric( as.duration(feedlog.list[[i]][, "StartTime"] - AssayStartTimeAbsolute) )
if ( length(feedlog.list[[i]][, "RelativeTime.s"][is.na(feedlog.list[[i]][, "RelativeTime.s"])]) > 0) {
stop("FeedStartTimeRelative not being calculated correctly. Check the format of the StartTime column.")
}
if ( range(feedlog.list[[i]][, "RelativeTime.s"])[1] < 0 ) {
stop("There are Feed Events that have a negative time stamp.")
print(paste("Please check the format of the StartTime columns in", list.files(feedlog.path)[i] ,sep = " "))
}
feedlog.list[[i]][, "FeedStartTimeRelative"] <- as.numeric( as.character(feedlog.list[[i]][, "RelativeTime.s"]) )
feedlog.list[[i]][, "RelativeTime.s"] <- NULL
# `dplyr` cannot understand the POSIX objects. Re-define them as vectors.
feedlog.list[[i]][, "StartTime"] <- as.character(feedlog.list[[i]][, "StartTime"])
} else {
feedlog.list[[i]][, "StartTime"] <- as.character(feedlog.list[[i]][, "StartTime"])
feedlog.list[[i]][, "FeedStartTimeRelative"] <- as.numeric( as.character(feedlog.list[[i]][, "RelativeTime.s"]) )
feedlog.list[[i]][, "RelativeTime.s"] <- NULL
}
# Add 1 to FeederIdx or ChoiceIdx, to match up with Food columns in metadata.
# Also, change both FeederIdx and ChoiceIdx to FoodIdx, so you can rbind later without problems.
if ("FeederIdx" %in% colnames(feedlog.list[[i]])) {
feedlog.list[[i]]$FeederIdx <- feedlog.list[[i]]$FeederIdx + 1
feedlog.list[[i]]$FoodIdx <- feedlog.list[[i]]$FeederIdx
feedlog.list[[i]]$FeederIdx <- NULL
} else if ("ChoiceIdx" %in% colnames(feedlog.list[[i]])) {
feedlog.list[[i]]$ChoiceIdx <- feedlog.list[[i]]$ChoiceIdx + 1
feedlog.list[[i]]$FoodIdx <- feedlog.list[[i]]$ChoiceIdx
feedlog.list[[i]]$ChoiceIdx <- NULL
}
# Add column indicating the original feedlog file from which the data comes from.
feedlog.list[[i]]$original.feedlog.file <- rep( names(feedlog.list)[i],
nrow(feedlog.list[[i]]) )
# Order the columns properly.
feedlog.list[[i]] <- as.data.table( feedlog.list[[i]] )
setcolorder(feedlog.list[[i]], colnames(feedlog.list[[1]]))
feedlog.list[[i]] <- data.frame(feedlog.list[[i]])
non.contrast.columns <- colnames(feedlog.list[[i]])
}
# Combine the feedlogs.
feedlog.all <- do.call('rbind', feedlog.list)
feedlog.all$Volume.mm3 <- as.numeric(as.character(feedlog.all$Volume.mm3))
# Save combined original data to a CSV file.
feedlog.original <- feedlog.all
write.csv(feedlog.original, file = paste(output.path, "/feedlog.original.combined.csv", sep = ""), row.names = FALSE)
# Filter feedlogs according to desired timeframe
feedlog.all <- filter(feedlog.all, FeedStartTimeRelative <= h * 3600)
write.csv(feedlog.all, file = paste(output.path, "/feedlog.original.combined.hour.zero.to", h, ".csv", sep = ""), row.names = FALSE)
```
```{r FeedLogAddNonFeedEvents}
# Get flies that did not feed.
feedlog.all[, "FoodIdx"] <- as.factor(feedlog.all[, "FoodIdx"])
no.feed.flies <- metadata.all[, "FlyID"][ !metadata.all[, "FlyID"] %in% feedlog.all[, "FlyID"] ]
# Add timebins to feedlog.all
n <- paste("bin.", as.character(bw/60), ".min", sep = "")
feedlog.all[, n] <- seq(0, h * 3600, bw)[findInterval(feedlog.all$FeedStartTimeRelative,
seq(0, h * 3600, bw))] + bw
feedlog.all[, n] <- factor(feedlog.all[, n], levels = seq(bw, h * 3600, bw) )
all.time.bins <- seq(bw, h * 3600, bw)
# Check that each fly has a feedlog for each food choice, at each timebin. If not, create a line that notes a null feed event.
tt <- feedlog.all %>%
group_by(FlyID, FoodIdx) %>%
summarise_( number.of.time.bins =
interp( ~length( levels(droplevels(n)) ), n = as.symbol(n) ),
missing.time.bins = interp( ~ paste(nn[ !nn %in%levels(droplevels(n))], collapse = ",") ,
n = as.symbol(n),
nn = as.name("all.time.bins") )
)
tt <- data.frame(filter(tt, number.of.time.bins != length(all.time.bins)))
# Make a list and add appropriate missing lines to the list.
temp.list <- list()
for ( rownum in 1:nrow(tt) ) {
missing.time.bins <- unlist(strsplit(tt[ rownum, "missing.time.bins"], split = "\\,"))
for (b in missing.time.bins) {
temp.row.name <- paste(tt[rownum, "FlyID"], # FlyID
tt[rownum, "FoodIdx"], # Food Choice
b, # Time bin
sep = "_")
temp.list[[temp.row.name]] <- list(StartTime = NA,
StartFrame = NA,
FeedTubeIdx = NA, # In the future also calculate the FeedTubeIdx.
FlyID = tt[rownum, "FlyID"],
AviFile = NA,
Volume.mm3 = 0,
Duration.ms = 0,
Evap.mm3.per.sec = NA,
Valid = NA,
ExperimentState = NA,
original.metadata.file = id.conversion[[as.character(tt[rownum, "FlyID"])]]$metadata.file,
original.feedlog.file = id.conversion[[as.character(tt[rownum, "FlyID"])]]$feedlog.file,
original.FlyID.feedlog = id.conversion[[as.character(tt[rownum, "FlyID"])]]$feedlog,
original.FlyID.metadata = id.conversion[[as.character(tt[rownum, "FlyID"])]]$metadata,
FeedStartTimeRelative = NA,
FoodIdx = tt[rownum, "FoodIdx"],
bin.temp = b)
temp.list[[temp.row.name]][[n]] <- temp.list[[temp.row.name]][["bin.temp"]]
temp.list[[temp.row.name]][["bin.temp"]] <- NULL
}
}
if ( length(levels(feedlog.all[, "FoodIdx"])) > 1) {
# Find flies that only fed on one food choice for the entire assay duration.
feedlog.food.choice.count <-
feedlog.all %>%
group_by(FlyID) %>%
summarise(food.choices.taken = length(levels(droplevels(FoodIdx))),
food.idx = paste(levels(droplevels(FoodIdx)), collapse = ", ") )
feedlog.food.choice.count <- data.frame(feedlog.food.choice.count)
feedlog.food.choice.count[, "food.choices.taken"] <- as.factor(feedlog.food.choice.count[, "food.choices.taken"])
just.one <- filter( feedlog.food.choice.count,
food.choices.taken == 1 ) # In the future, might want to change this to allow for more than 2 food choices....
rownames(just.one) <- just.one[, "FlyID"]
just.one[, "food.idx"] <- as.factor(just.one[, "food.idx"])
# This adds in lines for flies that only fed on one food choice, to note that they did not feed on the other food choice.
for (id in just.one[, "FlyID"]) {
missing.food.choices <- levels(feedlog.all$FoodIdx)[ !levels(feedlog.all$FoodIdx) %in% just.one[as.character(id), "food.idx"] ]
for (missing in missing.food.choices) {
for (b in seq(bw, h * 3600, bw)) {
temp.row.name <- paste(id, # FlyID
missing, # Food Choice
b, # Time bin
sep = "_")
temp.list[[temp.row.name]] <- list(StartTime = NA,
StartFrame = NA,
FeedTubeIdx = NA, # In the future also calculate the FeedTubeIdx.
FlyID = id,
AviFile = NA,
Volume.mm3 = 0,
Duration.ms = 0,
Evap.mm3.per.sec = NA,
Valid = NA,
ExperimentState = NA,
original.metadata.file = id.conversion[[as.character(tt[rownum, "FlyID"])]]$metadata.file,
original.feedlog.file = id.conversion[[as.character(tt[rownum, "FlyID"])]]$feedlog.file,
original.FlyID.feedlog = id.conversion[[as.character(tt[rownum, "FlyID"])]]$feedlog,
original.FlyID.metadata = id.conversion[[as.character(tt[rownum, "FlyID"])]]$metadata,
FeedStartTimeRelative = NA,
FoodIdx = missing,
bin.temp = b)
temp.list[[temp.row.name]][[n]] <- temp.list[[temp.row.name]][["bin.temp"]]
temp.list[[temp.row.name]][["bin.temp"]] <- NULL
}
}
}
}
# This creates lines for flies that did not feed into the feedlog, to note that they actually did not feed at all.
for (id in no.feed.flies) {
for (i in levels(feedlog.all$FoodIdx) ) {
for (b in seq(bw, h * 3600, bw)) {
temp.row.name <- paste(id, # FlyID
i, # Food Choice
b, # Time bin
sep = "_")
temp.list[[temp.row.name]] <- list(StartTime = NA,
StartFrame = NA,
FeedTubeIdx = NA, # In the future also calculate the FeedTubeIdx.
FlyID = id,
AviFile = NA,
Volume.mm3 = 0,
Duration.ms = 0,
Evap.mm3.per.sec = NA,
Valid = NA,
ExperimentState = NA,
original.metadata.file = id.conversion[[as.character(tt[rownum, "FlyID"])]]$metadata.file,
original.feedlog.file = id.conversion[[as.character(tt[rownum, "FlyID"])]]$feedlog.file,
original.FlyID.feedlog = id.conversion[[as.character(tt[rownum, "FlyID"])]]$feedlog,
original.FlyID.metadata = id.conversion[[as.character(tt[rownum, "FlyID"])]]$metadata,
FeedStartTimeRelative = NA,
FoodIdx = i,
bin.temp = b)
temp.list[[temp.row.name]][[n]] <- temp.list[[temp.row.name]][["bin.temp"]]
temp.list[[temp.row.name]][["bin.temp"]] <- NULL
}
}
}
# The magic of lapply -- turns each list element into a data.frame!
temp.list <- lapply(temp.list, as.data.frame)
# Make sure the column order in feedlog.all matches that in the other added dataframes.
setcolorder(feedlog.all,
colnames(temp.list[[1]]) )
# Add original feedlog to temp.list
temp.list[["original"]] <- feedlog.all
# Mush all the extra rows into feedlog.all
feedlog.all <- rbindlist(temp.list)
# Convert Volume.mm3 to Volume.nanoliter
feedlog.all <- mutate(feedlog.all, Volume.nanoliter = Volume.mm3 * 1000)
# Convert Duration.ms to Duration.s
feedlog.all <- mutate(feedlog.all, Duration.s = Duration.ms / 1000)
# Calculate feeding speed
feedlog.all <- mutate(feedlog.all, feeding.speed.nl.per.s = Volume.nanoliter/ Duration.s )
# Sort feedlog.all
feedlog.all <- arrange_(feedlog.all, "FlyID", "FoodIdx", n)
# removes temp.list to free up memory
rm(temp.list)
```
```{r CombineFeedLogAndMetaData}
# # Prep before joining
metadata.all$FlyID <- as.numeric(as.character(metadata.all$FlyID))
feedlog.all$FlyID <- as.numeric(as.character(feedlog.all$FlyID))
# Join (along columns) the feedlog and metadata by FlyID
rawdata.all <- full_join(feedlog.all, metadata.all, by = "FlyID")
# Get rid of duplicated columns.
rawdata.all$original.metadata.file.x <- NULL
rawdata.all$original.feedlog.file.x <- NULL
rawdata.all$original.FlyID.metadata.x <- NULL
rawdata.all$original.FlyID.feedlog.x <- NULL
rawdata.all$original.metadata.file <- rawdata.all$original.metadata.file.y
rawdata.all$original.feedlog.file <- rawdata.all$original.feedlog.file.y
rawdata.all$original.FlyID.metadata <- rawdata.all$original.FlyID.metadata.y
rawdata.all$original.FlyID.feedlog <- rawdata.all$original.FlyID.feedlog.y
rawdata.all$original.metadata.file.y <- NULL
rawdata.all$original.feedlog.file.y <- NULL
rawdata.all$original.FlyID.metadata.y <- NULL
rawdata.all$original.FlyID.feedlog.y <- NULL
# Convert FlyID in all three dataframes back to factor.
fly.id.levels <- as.character(sort(unique(metadata.all$FlyID)))
metadata.all$FlyID <- factor(metadata.all$FlyID, fly.id.levels)
feedlog.all$FlyID <- factor(feedlog.all$FlyID, fly.id.levels)
rawdata.all$FlyID <- factor(rawdata.all$FlyID, fly.id.levels)
```
```{r getAndSetContrasts}
# Assign FoodType to the feed events
for (rownum in 1:nrow(rawdata.all)) {
foodchoice.col <- paste("Food.", (rawdata.all[rownum, "FoodIdx"]), sep = "")
rawdata.all[rownum, "FoodType"] <- as.character(rawdata.all[rownum, paste(foodchoice.col)])
}
rawdata.all[, "FoodType"] <- as.factor(rawdata.all[, "FoodType"])
n <- paste("bin.", as.character(bw/60), ".min", sep = "")
food.columns <- paste("Food.", seq( 1:length(levels(rawdata.all$FoodIdx)) ), sep = "")
to.drop <- c("StartTime", "StartFrame", "FeedTubeIdx", "FlyID", "AviFile",
"Volume.mm3", "Volume.nanoliter", "Duration.ms", "Duration.s", "Evap.mm3.s", "Evap.mm3.per.sec",
"original.metadata.file", "original.feedlog.file",
"original.FlyID.metadata", "original.FlyID.feedlog",
"Valid", "ExperimentState", "FeedStartTimeRelative", "FoodIdx",
"feeding.speed.nl.per.s", "Food.1", "Food.2", n)
to.check <- colnames(rawdata.all)[!colnames(rawdata.all) %in% to.drop]
# Check which columns have more than one level.
for (c in to.check) {
if ( length( levels( as.factor( rawdata.all[, c] ) ) ) == 1) {
to.drop <- append(to.drop, c)
}
}
# Then remove these columns from consideration, leaving us with the contrasts to crunch.
contrast.columns <- to.check[!to.check %in% to.drop]
contrast.columns.noFoodType <- contrast.columns[!contrast.columns %in% c("FoodType")]
```
```{r SetContrastReferenceLevels}
# Code below to remove only columns that are entirely NA from
# http://stackoverflow.com/questions/15968494/how-to-delete-columns-with-na-in-r
rawdata.all <- rawdata.all[, !apply( rawdata.all, 2, function(x) all(is.na(x)))]
# Get rid of any feed events falling outside the experiment duration
rawdata.all[, "FeedStartTimeRelative"][is.na(rawdata.all[, "FeedStartTimeRelative"])] <- 0
rawdata.all[, "FeedStartTimeRelative"] <- as.numeric(as.character(rawdata.all[, "FeedStartTimeRelative"]))
rawdata.all <- filter(rawdata.all, FeedStartTimeRelative < h * 3600)
rawdata.all[, "FeedStartTimeRelative"][rawdata.all[, "FeedStartTimeRelative"] == 0] <- NA
# Read in levels.
temp.contrasts <- read.csv( file=paste(file.path,"/reference_levels.txt", sep = ""), header = FALSE)
temp.contrasts[temp.contrasts == ""] <- NA # Fills in empty cells with "NA".
reflevels <- list()
for (row in 2:nrow(temp.contrasts)) {
x <- temp.contrasts[row, ][!is.na(temp.contrasts[row, ])] # removes NA from row
reflevels[[ as.character(temp.contrasts[row, 1]) ]] <- toupper( x[2:length(x)] ) # Adds the ordered levels to the contrast list, as uppercase text.
}
# Makes sure contrast columns are factors, and to mitigate against capitalization errors.
# Then set order of levels for each experimental contrast, according to that dictated in `reference_levels.txt`.
for (i in contrast.columns) {
rawdata.all[,i] <- toupper(rawdata.all[,i])
rawdata.all[,i] <- factor(rawdata.all[,i], reflevels[[i]])
}
# Check that all contrast levels are captured correctly in `reference_levels.txt`.
if ( all.equal(names(reflevels), contrast.columns) != TRUE ) {
stop("Contrast Levels in `reference_levels.txt` do not match the set of columns in the metadata with contrasts. Please check that all factors with contrasts (across all feedlogs) are indicated in `reference_levels.txt`.")
}
for (x in names(reflevels)) {
if ( all.equal(levels(rawdata.all[, x]), reflevels[[x]] ) != TRUE) {
error.msg <- paste("The levels in", x, "do not match between the metadata and `reference_levels.txt`. Please check `reference_levels.txt` again.")
stop(error.msg)
}
}
rawdata.all <- arrange_(rawdata.all, contrast.columns) # VERY IMPORTANT -- ORDERS THE DATAFRAME AS DESIRED.
# Create new column in `rawdata.all` to combine all contrasts, without Food.
rawdata.all <- unite_(rawdata.all, "contrast.groups.noFoodType", contrast.columns.noFoodType, sep = "\n", remove = FALSE)
# Create new column in `rawdata.all` to combine all contrasts, with Food.
rawdata.all <- unite_(rawdata.all, "contrast.groups.withFoodType", contrast.columns, sep = "\n", remove = FALSE)
# Create new column in `rawdata.all` to combine contrasts with FlyID.
rawdata.all <- unite_(rawdata.all, "FlyID.contrast.groups.withFoodType", c("FlyID", contrast.columns), sep = "\n", remove = FALSE)
# Set order of levels of combined contrast groups, according to that dictated in `reference_levels.txt` and in `reflevels`.
reflevels.combis <- expand.grid(reflevels) # Creates a dataframe with all combinations of contrast levels.
reflevels.combis <- unite_(reflevels.combis, "contrast.groups.noFoodType", contrast.columns.noFoodType, sep = "\n", remove = FALSE)
reflevels.combis <- unite_(reflevels.combis, "contrast.groups.withFoodType", contrast.columns, sep = "\n", remove = FALSE)
rawdata.all[, "contrast.groups.withFoodType"] <- factor(rawdata.all[, "contrast.groups.withFoodType"],
unique(reflevels.combis$contrast.groups.withFoodType) )
rawdata.all[, "contrast.groups.noFoodType"] <- factor(rawdata.all[, "contrast.groups.noFoodType"],
unique(reflevels.combis$contrast.groups.noFoodType) )
```
```{r IdentifyContrastNumbers}
contrast.numbers <- list()
t <- dplyr::select( metadata.all, one_of(contrast.columns[!contrast.columns %in% c("FoodType")]) )
# Loop below turns all contrast groups (no Food Type) into uppercase, to match the contrast column factors.
for ( c in colnames(t) ) {
t[, c] <- toupper(t[, c])
}
t <- dplyr::mutate(t, x = apply(t, 1, paste, collapse = "\n"))
contrast.numbers <- plyr::count(t, "x")
rownames(contrast.numbers) <- contrast.numbers[, "x"]
contrast.numbers[, "total.fly.count"] <- contrast.numbers[, "freq"]
contrast.numbers[, "freq"] <- NULL
contrast.numbers[, "x"] <- NULL
contrast.numbers[, "contrast.groups.noFoodType"] <- factor(rownames(contrast.numbers))
contrast.numbers[, "active.fly.count"] <- contrast.numbers[, "total.fly.count"]
# Find out which contrast group the non-feeding flies belong to.
no.feed.flies.metadata <- metadata.all[as.numeric(metadata.all[, "FlyID"][metadata.all[, "FlyID"] %in% no.feed.flies]), ]
t <- dplyr::select( no.feed.flies.metadata, one_of(contrast.columns[!contrast.columns %in% c("FoodType")]) )
t <- dplyr::mutate(t, x = apply(t, 1, paste, collapse = "\n"))
no.feed.flies.metadata[, "contrast.groups.noFoodType"] <- as.factor(t[, "x"])
nonactive.flies <- plyr::count(no.feed.flies.metadata, "contrast.groups.noFoodType")
rownames(nonactive.flies) <- nonactive.flies[, "contrast.groups.noFoodType"]
for (c in rownames(nonactive.flies)) {
contrast.numbers[c, "active.fly.count"] <- contrast.numbers[c, "active.fly.count"] - nonactive.flies[c, "freq"]
}
```
```{r CumulativeVolumeDrunk}
n <- paste("bin.", as.character(bw/60), ".min", sep = "")
rawdata.all <- arrange_(rawdata.all, "FlyID", "FeedStartTimeRelative")
cols <- c("contrast.groups.withFoodType", "FlyID")
dots <- lapply(cols, as.symbol)
rawdata.all <-
rawdata.all %>%
group_by_(.dots = dots) %>%
mutate(cumulative.vol.nanoliter = cumsum(Volume.nanoliter) )
rawdata.all <- data.frame(rawdata.all)
rawdata.all[, "FlyID.contrast.groups.withFoodType"] <- factor(rawdata.all[, "FlyID.contrast.groups.withFoodType"])
# Make sure that binned column is numeric.
rawdata.all[, n] <- as.numeric ( as.character(rawdata.all[, n]) )
write.csv(rawdata.all, file = paste(output.path, "/rawdata.all.processed.csv", sep = ""), row.names = FALSE)
```
```{r summaryPerFly}
# See http://stackoverflow.com/questions/21208801/group-by-multiple-columns-in-dplyr-using-string-vector-input
cols <- unique(c(contrast.columns, "FoodType", "FlyID")) # Need to group_by FoodType, regardless of whether it is a contrast factor or not.
dots <- lapply(cols, as.symbol)
summary.per.fly <-
rawdata.all %>%
group_by_(.dots = dots) %>% # Don't forget the second underscore for non-standard evaluation.
summarise(total.feed.count = length( na.exclude(StartTime) ),
time.to.first.feed.s = min( FeedStartTimeRelative, na.rm = TRUE ),
total.vol.intake.nanoliter = sum(Volume.nanoliter))
# Create temp.rawdata, where all null feed events are marked with an NA.
temp.rawdata <- rawdata.all
temp.rawdata[, "Volume.mm3"][temp.rawdata[, "Volume.mm3"] == 0] <- NA
temp.rawdata[, "Duration.ms"][temp.rawdata[, "Duration.ms"] == 0] <- NA
temp.rawdata[, "Volume.nanoliter"][temp.rawdata[, "Volume.nanoliter"] == 0] <- NA
temp.rawdata[, "Duration.s"][temp.rawdata[, "Duration.s"] == 0] <- NA
extra.cols <-
temp.rawdata %>%
group_by_(.dots = dots) %>%
summarise(total.feed.duration.s = sum(Duration.s, na.rm = TRUE),
mean.feed.duration.s = mean(Duration.s, na.rm = TRUE),
median.feed.duration.s = median(Duration.s, na.rm = TRUE),
sd.feed.duration.s = sd(Duration.s, na.rm = TRUE),
ci.lower.feed.duration.s = mean.feed.duration.s -
1.96 * ( sd.feed.duration.s / sqrt( length(na.exclude(Duration.s))) ),
ci.upper.feed.duration.s = mean.feed.duration.s +
1.96 * ( sd.feed.duration.s / sqrt( length(na.exclude(Duration.s))) ),
mean.feeding.speed.nl.per.s = mean(na.exclude(feeding.speed.nl.per.s)),
median.feeding.speed.nl.per.s = median(na.exclude(feeding.speed.nl.per.s)),
sd.feeding.speed.nl.per.s = sd(na.exclude(feeding.speed.nl.per.s)),
ci.lower.feeding.speed.nl.per.s = mean.feeding.speed.nl.per.s -
1.96 * (sd.feeding.speed.nl.per.s / sqrt(length(na.exclude(feeding.speed.nl.per.s))) ),
ci.upper.feeding.speed.nl.per.s = mean.feeding.speed.nl.per.s +
1.96 * (sd.feeding.speed.nl.per.s / sqrt(length(na.exclude(feeding.speed.nl.per.s))) ),
mean.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)),
median.vol.per.feed.nanoliter = median(na.exclude(Volume.nanoliter)),
sd.vol.per.feed.nanoliter = sd(na.exclude(Volume.nanoliter)),
ci.lower.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)) -
1.96 * ( sd(na.exclude(Volume.nanoliter)) / sqrt(length(na.exclude(Volume.nanoliter))) ),
ci.upper.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)) +
1.96 * ( sd(na.exclude(Volume.nanoliter)) / sqrt(length(na.exclude(Volume.nanoliter))) ))
# Remove the table.frame attributes so select_ and arrange_ works properly.
summary.per.fly <- as.data.frame(summary.per.fly)
extra.cols <- data.frame(extra.cols)
summary.per.fly <- left_join(summary.per.fly, extra.cols,
by = cols)
summary.per.fly <- data.frame(summary.per.fly)
for (c in contrast.columns) {
summary.per.fly[, c] <- factor(summary.per.fly[, c], reflevels[[c]])
summary.per.fly <- arrange_(summary.per.fly, c) # VERY IMPORTANT -- ORDERS THE DATAFRAME AS DESIRED.
}
# Set CIs that drop below 0, to 0.
for (c in c("ci.lower.feed.duration.s",
"ci.lower.feeding.speed.nl.per.s",
"ci.lower.vol.per.feed.nanoliter") ) {
summary.per.fly[, c][summary.per.fly[, c] < 0] <- 0
}
write.csv(summary.per.fly, file = paste(output.path, "/summary.per.fly.csv", sep = ""), row.names = FALSE)
# Create new column in `summary.per.fly` to combine all contrasts, without Food.
summary.per.fly <- unite_(summary.per.fly, "contrast.groups.noFoodType", contrast.columns.noFoodType, sep = "\n", remove = FALSE)
# Create new column in `summary.per.fly` to combine all contrasts, with Food.
summary.per.fly <- unite_(summary.per.fly, "contrast.groups.withFoodType", contrast.columns, sep = "\n", remove = FALSE)
# Set order of levels of combined contrast groups, according to that dictated in `reference_levels.txt`.
summary.per.fly[, "contrast.groups.withFoodType"] <- factor(summary.per.fly[, "contrast.groups.withFoodType"],
unique(reflevels.combis$contrast.groups.withFoodType))
summary.per.fly[, "contrast.groups.noFoodType"] <- factor(summary.per.fly[, "contrast.groups.noFoodType"],
unique(reflevels.combis$contrast.groups.noFoodType))
```
```{r summaryPerContrastGroupWithFood}
temp.perFly <- summary.per.fly
temp.perFly[, "total.feed.count"][temp.perFly[, "total.feed.count"] == 0] <- NA
if ( length(levels(rawdata.all[, "FoodIdx"])) > 1 ) {
cols <- unique(c(contrast.columns, "FoodType"))
# Need to group_by FoodType, regardless of whether it is a contrast factor or not.
dots <- lapply(cols, as.symbol)
summary.per.contrastGroup.withFood <-
temp.rawdata %>%
group_by_(.dots = dots) %>% # Don't forget the second underscore for non-standard evaluation.
summarise(total.feed.duration.s = sum(Duration.s, na.rm = TRUE),
mean.feed.duration.s = mean(Duration.s, na.rm = TRUE),
median.feed.duration.s = median(Duration.s, na.rm = TRUE),
sd.feed.duration.s = sd(Duration.s, na.rm = TRUE),
ci.lower.feed.duration.s = mean.feed.duration.s -
1.96 * ( sd.feed.duration.s / sqrt( length(na.exclude(Duration.s))) ),
ci.upper.feed.duration.s = mean.feed.duration.s +
1.96 * ( sd.feed.duration.s / sqrt( length(na.exclude(Duration.s))) ),
mean.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)),
median.vol.per.feed.nanoliter = median(na.exclude(Volume.nanoliter)),
sd.vol.per.feed.nanoliter = sd(na.exclude(Volume.nanoliter)),
ci.lower.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)) -
1.96 * ( sd(na.exclude(Volume.nanoliter)) / sqrt(length(na.exclude(Volume.nanoliter))) ),
ci.upper.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)) +
1.96 * ( sd(na.exclude(Volume.nanoliter)) / sqrt(length(na.exclude(Volume.nanoliter))) ),
mean.feeding.speed.nl.per.s = mean(na.exclude(feeding.speed.nl.per.s)),
median.feeding.speed.nl.per.s = median(na.exclude(feeding.speed.nl.per.s)),
sd.feeding.speed.nl.per.s = sd(na.exclude(feeding.speed.nl.per.s)),
ci.lower.feeding.speed.nl.per.s = mean.feeding.speed.nl.per.s -
1.96 * (sd.feeding.speed.nl.per.s / sqrt(length(na.exclude(feeding.speed.nl.per.s))) ),
ci.upper.feeding.speed.nl.per.s = mean.feeding.speed.nl.per.s +
1.96 * (sd.feeding.speed.nl.per.s / sqrt(length(na.exclude(feeding.speed.nl.per.s))) ))
extra <-
summary.per.fly %>%
group_by_(.dots = dots) %>%
summarise(sum.feed.count = sum(total.feed.count),
mean.total.feed.count.per.fly = mean(total.feed.count),
median.total.feed.count.per.fly = median(total.feed.count),
sd.total.feed.count.per.fly = sd(total.feed.count),
ci.lower.mean.total.feed.count.per.fly = mean(total.feed.count) -
1.96 * ( sd(total.feed.count) / sqrt(length(total.feed.count)) ),
ci.upper.mean.total.feed.count.per.fly = mean(total.feed.count) +
1.96 * ( sd(total.feed.count) / sqrt(length(total.feed.count)) ),
mean.vol.per.feed.per.fly.nanoliter = mean(na.exclude(mean.vol.per.feed.nanoliter)),
median.vol.per.feed.per.fly.nanoliter = median(na.exclude(mean.vol.per.feed.nanoliter)),
sd.vol.per.feed.per.fly.nanoliter = sd(na.exclude(mean.vol.per.feed.nanoliter)),
ci.lower.vol.per.feed.per.fly.nanoliter = mean(na.exclude(mean.vol.per.feed.nanoliter)) -
1.96 * ( sd(na.exclude(mean.vol.per.feed.nanoliter)) / sqrt(length(na.exclude(mean.vol.per.feed.nanoliter))) ),
ci.upper.vol.per.feed.per.fly.nanoliter = mean(na.exclude(mean.vol.per.feed.nanoliter)) +
1.96 * ( sd(na.exclude(mean.vol.per.feed.nanoliter)) / sqrt(length(na.exclude(mean.vol.per.feed.nanoliter))) ),
mean.feeding.speed.per.fly.nl.per.s = mean(na.exclude(mean.feeding.speed.nl.per.s)),
median.feeding.speed.per.fly.nl.per.s = median(na.exclude(mean.feeding.speed.nl.per.s)),
sd.feeding.speed.per.fly.nl.per.s = sd(na.exclude(mean.feeding.speed.nl.per.s)),
ci.lower.feeding.speed.per.fly.nl.per.s = mean.feeding.speed.per.fly.nl.per.s -
1.96 * (sd.feeding.speed.per.fly.nl.per.s / sqrt(length(na.exclude(mean.feeding.speed.nl.per.s))) ),
ci.upper.feeding.speed.per.fly.nl.per.s = mean.feeding.speed.per.fly.nl.per.s +
1.96 * (sd.feeding.speed.per.fly.nl.per.s / sqrt(length(na.exclude(mean.feeding.speed.nl.per.s))) ),
grand.total.vol.intake.nanoliter = sum(total.vol.intake.nanoliter),
mean.total.vol.intake.nanoliter = mean(total.vol.intake.nanoliter),
median.total.vol.intake.nanoliter = median(total.vol.intake.nanoliter),
sd.mean.total.vol.intake.nanoliter = sd(total.vol.intake.nanoliter),
ci.lower.mean.total.vol.intake.nanoliter = mean(total.vol.intake.nanoliter) -
1.96 * ( sd(total.vol.intake.nanoliter) / sqrt(length(total.vol.intake.nanoliter)) ),
ci.upper.mean.total.vol.intake.nanoliter = mean(total.vol.intake.nanoliter) +
1.96 * ( sd(total.vol.intake.nanoliter) / sqrt(length(total.vol.intake.nanoliter)) ),
mean.time.to.first.feed.s = mean(na.exclude(time.to.first.feed.s)),
median.time.to.first.feed.s = median(na.exclude(time.to.first.feed.s)),
sd.time.to.first.feed.s = sd(na.exclude(time.to.first.feed.s)),
ci.lower.time.to.first.feed.s = mean(na.exclude(time.to.first.feed.s)) -
1.96 * ( sd(na.exclude(time.to.first.feed.s)) / sqrt(length(na.exclude(time.to.first.feed.s))) ),
ci.upper.time.to.first.feed.s = mean(na.exclude(time.to.first.feed.s)) +
1.96 * ( sd(na.exclude(time.to.first.feed.s)) / sqrt(length(na.exclude(time.to.first.feed.s))) ) )
extra.cols <- temp.perFly %>%
group_by_(.dots = dots) %>%
summarise(total.fly.count = length(total.feed.count),
feeding.fly.count = length(na.exclude(total.feed.count)))
# Obtain friendly dataframes.
summary.per.contrastGroup.withFood <- data.frame(summary.per.contrastGroup.withFood)
extra <- data.frame(extra)
extra.cols <- data.frame(extra.cols)
# Then join them.
summary.per.contrastGroup.withFood <- left_join(extra.cols,
left_join(extra,
summary.per.contrastGroup.withFood,
by = cols),
by = cols)
# Joining the dataframes might coerce the contrast columns into characters. This fixes that.
for (c in contrast.columns) {
summary.per.contrastGroup.withFood[, c]<- factor(summary.per.contrastGroup.withFood[, c], levels = reflevels[[c]])
}
# Then round to nice significant digits.
for (c in colnames(summary.per.contrastGroup.withFood) ) {
if ( is.numeric(summary.per.contrastGroup.withFood[, c]) &&
abs(range(summary.per.contrastGroup.withFood[, c], na.rm = TRUE)[2]) < 1) {
summary.per.contrastGroup.withFood[, c] <- signif(summary.per.contrastGroup.withFood[, c], digits = 3)
} else if (is.numeric(summary.per.contrastGroup.withFood[, c]) &&
abs(range(summary.per.contrastGroup.withFood[, c], na.rm = TRUE)[2]) > 1) {
summary.per.contrastGroup.withFood[, c] <- round(summary.per.contrastGroup.withFood[, c], digits = 2)
}
}
# Set CIs that drop below 0, to 0.
for (c in c("ci.lower.vol.per.feed.nanoliter",
"ci.lower.feeding.speed.nl.per.s",
"ci.lower.vol.per.feed.per.fly.nanoliter",
"ci.lower.feeding.speed.per.fly.nl.per.s",
"ci.lower.feed.duration.s",
"ci.lower.mean.total.feed.count.per.fly",
"ci.lower.mean.total.vol.intake.nanoliter",
"ci.lower.time.to.first.feed.s") ) {
summary.per.contrastGroup.withFood[, c][summary.per.contrastGroup.withFood[, c] < 0] <- 0
}
summary.per.contrastGroup.withFood <- data.frame(summary.per.contrastGroup.withFood)
# Ensures that the dataframe is sorted according to the factor level order we want.
for (c in contrast.columns) {
summary.per.contrastGroup.withFood[, c] <- factor(summary.per.contrastGroup.withFood[, c], reflevels[[c]])
summary.per.contrastGroup.withFood <- arrange_(summary.per.contrastGroup.withFood, c) # VERY IMPORTANT -- ORDERS THE DATAFRAME AS DESIRED.
}
# Write to file.
write.csv(summary.per.contrastGroup.withFood,
file = paste(output.path, "/summary.per.contrastGroup.withFood.csv", sep = ""),
row.names = FALSE)
# Create new column in `summary.per.contrastGroup.withFood` to combine all contrasts, with Food.
summary.per.contrastGroup.withFood <- unite_(summary.per.contrastGroup.withFood,
"contrast.groups.withFoodType",
contrast.columns, sep = "\n", remove = FALSE)
# Create new column in `summary.per.contrastGroup.withFood` to combine all contrasts, without Food.
summary.per.contrastGroup.withFood <- unite_(summary.per.contrastGroup.withFood,
"contrast.groups.noFoodType",
contrast.columns.noFoodType, sep = "\n", remove = FALSE)
# Set order of levels of combined contrast groups, according to that dictated in `reference_levels.txt`.
summary.per.contrastGroup.withFood[, "contrast.groups.withFoodType"] <- factor(summary.per.contrastGroup.withFood[, "contrast.groups.withFoodType"],
unique(reflevels.combis$contrast.groups.withFoodType))
summary.per.contrastGroup.withFood[, "contrast.groups.noFoodType"] <- factor(summary.per.contrastGroup.withFood[, "contrast.groups.noFoodType"],
unique(reflevels.combis$contrast.groups.noFoodType))
}
```
```{r summaryPerContrastGroupNoFood}
cols <- contrast.columns.noFoodType
dots <- lapply(cols, as.symbol)
summary.per.contrastGroup.noFood <-
temp.rawdata %>%
group_by_(.dots = dots) %>% # Don't forget the second underscore for non-standard evaluation.
summarise(total.feed.duration.s = sum(Duration.s, na.rm = TRUE),
mean.feed.duration.s = mean(Duration.s, na.rm = TRUE),
median.feed.duration.s = median(Duration.s, na.rm = TRUE),
sd.feed.duration.s = sd(Duration.s, na.rm = TRUE),
ci.lower.feed.duration.s = mean.feed.duration.s -
1.96 * ( sd.feed.duration.s / sqrt( length(na.exclude(Duration.s))) ),
ci.upper.feed.duration.s = mean.feed.duration.s +
1.96 * ( sd.feed.duration.s / sqrt( length(na.exclude(Duration.s))) ),
mean.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)),
median.vol.per.feed.nanoliter = median(na.exclude(Volume.nanoliter)),
sd.vol.per.feed.nanoliter = sd(na.exclude(Volume.nanoliter)),
ci.lower.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)) -
1.96 * ( sd(na.exclude(Volume.nanoliter)) / sqrt(length(na.exclude(Volume.nanoliter))) ),
ci.upper.vol.per.feed.nanoliter = mean(na.exclude(Volume.nanoliter)) +
1.96 * ( sd(na.exclude(Volume.nanoliter)) / sqrt(length(na.exclude(Volume.nanoliter))) ),
mean.feeding.speed.nl.per.s = mean(na.exclude(feeding.speed.nl.per.s)),
median.feeding.speed.nl.per.s = median(na.exclude(feeding.speed.nl.per.s)),
sd.feeding.speed.nl.per.s = sd(na.exclude(feeding.speed.nl.per.s)),
ci.lower.feeding.speed.nl.per.s = mean.feeding.speed.nl.per.s -
1.96 * (sd.feeding.speed.nl.per.s / sqrt(length(na.exclude(feeding.speed.nl.per.s))) ),
ci.upper.feeding.speed.nl.per.s = mean.feeding.speed.nl.per.s +
1.96 * (sd.feeding.speed.nl.per.s / sqrt(length(na.exclude(feeding.speed.nl.per.s))) ))
extra <-
summary.per.fly %>%
group_by_(.dots = dots) %>%
summarise(sum.feed.count = sum(total.feed.count),
mean.total.feed.count.per.fly = mean(total.feed.count),
median.total.feed.count.per.fly = median(total.feed.count),
sd.total.feed.count.per.fly = sd(total.feed.count),