-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_tidying.R
2226 lines (1691 loc) · 63.6 KB
/
data_tidying.R
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: Lepidoptera data tidying for raw data
# author: Esteban Menares
# date: Aug 2021
# NOTE: many of the datasets were obtained from BExIS (BExIS (https://www.bexis.uni-jena.de/). Use the indicated ID (and version) to search the original datasets on their website.
# Setup ---------------------------------------------------------------
library(tidyverse) # for data wrangling
library(data.table) # for data wrangling
source('scripts/source_script.R')
# 1. OCCURRENCES -------------------------------------------------------
# read in data
# lepi: table with butterfly abundances. They counted all species and their individual numbers within 2.5 m either side and 5 m in front of the scientists on transects of 300 m length within 30 min. A transect was divided in 50m of 5 min intervals. 3 surveys on all plots.
# BExIS ID # 12526 (1.8.19)
# Börschig C, Klein A-M, von Wehrden H, Krauss J (2013) Traits of butterfly communities change from specialist to generalist characteristics with increasing land-use intensity. Basic and Applied Ecology 14:547–554. https://doi.org/10.1016/j.baae.2013.09.002
lepi <-
readxl::read_xlsx("/Users/estebanmenaresbarraza/Documents/BTU-PhD/troph-cost/resources_troph-cost/12526_Lepidoptera-2008-OpenData/12526.xlsx",
sheet = "12526",
na = "NA")
# Plant cover table: In spring of the years 2008-2020, we sampled all species in an area of 4m x 4m and estimated the percentage cover of each species relative to the whole 4 m x 4 m plot. The vegetation records are done in early summer, normally in May and beginning of June. NA = Missing data, because already mown or not accessible because of grazing animals
# BExIS ID # 23586 (1.3.1)
plants <-
readxl::read_xlsx("/Users/estebanmenaresbarraza/Documents/BTU-PhD/troph-cost/resources_troph-cost/23586_Vegetation_BExIS-OpenData/23586.xlsx",
sheet = "data_2008-2017",
na = "NA")
# tidy data
# Lepi
lepi_new <-
lepi %>%
# remove moths
filter(but_moth == "B") %>%
arrange(species, EPID, date) %>%
# sum up abundances over all intervals i.e. total abundance per survey, EPID, species
group_by(species, EPID, survey) %>%
summarise(abundance = sum(abundance), .groups = "drop") %>%
# average the summed up abundances over all surveys i.e. total abundance for the whole year per species and EPID
group_by(species, EPID) %>%
summarise(abundance = mean(abundance), .groups = "drop") %>%
mutate(# add underscore to names
species = str_replace_all(species, ' ', "_")) %>%
# put species names as cols
pivot_wider(
.,
names_from = species,
values_from = abundance,
values_fill = 0
) %>%
# sum values of Pyrgus_alveus + Pyrgus_alveus_Komplex because is hard to separate
mutate(Pyrgus_alveus_Komplex = Pyrgus_alveus + Pyrgus_alveus_Komplex) %>%
# drop unneeded cols
select(-Pyrgus_alveus) %>%
rename(Leptidea_sinapis_complex = `Leptidea_sinapis/reali`,
Melitaea_athalia = `Melitaea_athalia-Komplex`,
Pyrgus_alveus_complex = Pyrgus_alveus_Komplex) %>%
# round values to have no decimals
mutate(across(where(is.numeric), round, 0)) %>%
# arrange by plot
arrange(EPID)
# plants
plant_new <-
plants %>%
filter(Year == "2008") %>%
# per plant species, average all cover values for all sites
group_by(Species, Useful_EP_PlotID) %>%
summarise(abundance = mean(Cover), .groups = "drop") %>%
rename(species = Species,
EPID = Useful_EP_PlotID) %>%
pivot_wider(
.,
names_from = species,
values_from = abundance,
values_fill = 0
) %>%
# remove unnecessary observations
select(
-c(
Brassicaceae_sp,
Asteraceae_sp,
Caryophyllaceae_sp,
Orchidacea_sp,
Baumkeimling_sp,
Unknown,
Rhinanthus_aggr.,
# Tree species
Acer_sp,
Betula_pendula,
Carpinus_betulus,
Fraxinus_excelsior,
Pinus_sylvestris,
Populus_tremula,
Prunus_avium,
Prunus_sp,
Prunus_spinosa,
Quercus_robur,
Tilia_sp,
# Shrubs species
Juniperus_communis,
Crataegus_sp,
# fern species
Ophioglossum_vulgatum
)
) %>%
# rename species names to have only genus_species
rename(
Achillea_millefolium = Achillea_millefolium_aggr.,
Alchemilla_vulgaris = Alchemilla_vulgaris_aggr.,
Allium_oleraceum = Allium_cf_oleraceum,
Arabis_hirsuta = Arabis_hirsuta_aggr.,
Bromus_hordeaceus = Bromus_hordeaceus_aggr.incl_B_commutatus,
Carex_muricata = Carex_muricata_aggr.,
Cerastium_pumilum = Cerastium_pumilum_aggr.,
Euphrasia_rostkoviana = Euphrasia_rostkoviana_aggr.,
Euphrasia_sp = Euphrasia_sp_cf,
Festuca_ovina = Festuca_ovina_aggr.,
Festuca_rubra = Festuca_rubra_aggr.,
Galium_mollugo = Galium_mollugo_aggr.,
Hordeum_vulgare = Hordeum_vulgare_aggr.,
Leucanthemum_vulgare = Leucanthemum_vulgare_aggr.,
Medicago_sativa = Medicago_sativa_aggr.,
Muscari_neglectum = Muscari_neglectum_aggr.,
Odontites_vernus = Odontites_vernus_aggr.,
Ononis_spinosa = Ononis_repens_spinosa_aggr.,
Phleum_pratense = Phleum_pratense_aggr.,
Pimpinella_saxifraga = Pimpinella_saxifraga_aggr.,
Poa_pratensis = Poa_pratensis_aggr.,
Polygala_comosa = Polygala_comosa_aggr.,
Potentilla_verna = Potentilla_verna_aggr.,
Rosa_canina = Rosa_canina_aggr.,
Vicia_cracca = Vicia_cracca_aggr.,
Vicia_sativa = Vicia_sativa_aggr.,
Vicia_tetrasperma = Vicia_tetrasperma_aggr.
)
# join both df
occur_new <-
lepi_new %>%
inner_join(
plant_new,
by = "EPID"
)
# write_csv(occur_new, 'data/raw/occur.csv', quote = "none") # use quote = none to avoid "" on NAs)
# 2. LANDUSE -------------------------------------------------------------
#' **Aim**: to create a dataset containing all information for experimental
#' sites including lad use data
# Read in data
vogt <- read_delim('resources_troph-cost/338774_Vogt_et_at_2019_Landuse-OpenData/338774_Vogt_et_at_2019.csv')
obs <-
read_csv('data/raw/cooccurAll.csv')
# Data tidying
vogt <-
vogt %>%
# rename variable as in other datasets
rename(EPID = PlotID) %>%
# filter out region HAI and EPIDs that don't have occurrences
filter(StudyRegion != 'HAI') %>%
# add a leading zero
mutate(
EPID = EPID %>%
str_replace('(AEG|SEG)([1-9]{1})$', # create groups for regex
'\\10\\2')) %>% # add a leading zero between groups
# create a new ID col from unite Year and EPID
unite(.,
EPID,
Year,
col = 'ID_new',
sep = '_',
remove = FALSE) %>%
# cleaning up...
select(-ID) %>%
relocate(ID_new, StudyRegion:DescSeeds) %>%
rename(ID = ID_new) %>%
# set dates as date (year, month, day)
mutate(across(c(Date, DateMowing1, DateMowing2, DateMowing3,DateMowing4),
~ dmy(.x)))
# write_csv(vogt, file = 'data/raw/sites_landuse.csv')
# Create vectos with EPIDs for site SCH and ALB where species have occurrences
EP_to_filter <-
obs %>%
filter(
str_detect(EPID, 'SEG|AEG')) %>%
column_to_rownames('EPID') %>%
select(
where(
~ sum(.x) !=0)) %>%
row.names()
# filter sites from year 2007 and 2008 and that have occurrences
sites <-
vogt %>%
filter(Year == 2008 | Year == 2007) %>%
filter(EPID %in% EP_to_filter)
# write_csv(sites, file = 'data/raw/sites_landuse_2007-2008.csv')
# 3. TROPHIC INTERACTIONS -------------------------------------------------
# NOTE: this data were extracted from Ebert (2005) for ALB, and Richert and Brauner (2018) for SCH, then collected in a single excel file which then was here cleaned up. Cleaned versions with a single file per region for larva and adults were stored in BExIS as long format and can be found using the ID:
# Imago ALB: 31734
# Larva ALB: 31735
# Imago SCH: 31736
# Larva SCH: 31737
# we then use them in ~troph-cost/scripts/wrangling/pairs_1_trophic_links.R in wide format to perform the analyses of co-occurrence and other posterior analyses.
## 3.1 Larva_BB (Berlin Brandenburg = BB = SCH)
Larva_BB <-
readxl::read_xlsx("/Users/estebanmenaresbarraza/Documents/BTU-PhD/troph-cost/resources_troph-cost/trophic-interactions/trophic-links_matrix_lepidoptera_plants.xlsx", sheet = "Larva_BB", na = "NA") %>%
# rename butterfly names
rename(Leptidea_sinapis_complex = Leptidea_sinapis_reali,
Melitaea_athalia = Melitaea_athalia_Komplex,
Pyrgus_alveus_complex = Pyrgus_alveus_Komplex)
## 3.2 Larva_BW (Baden-Württemberg = BW = ALB)
Larva_BW <-
readxl::read_xlsx("/Users/estebanmenaresbarraza/Documents/BTU-PhD/troph-cost/resources_troph-cost/trophic-interactions/trophic-links_matrix_lepidoptera_plants.xlsx", sheet = "Larva_BW", na = "NA") %>%
# rename butterfly names
rename(Leptidea_sinapis_complex = Leptidea_sinapis_reali,
Melitaea_athalia = Melitaea_athalia_Komplex,
Pyrgus_alveus_complex = Pyrgus_alveus_Komplex)
## 3.3 Imago_BB (Berlin Brandenburg = BB = SCH)
Imago_BB <-
readxl::read_xlsx("/Users/estebanmenaresbarraza/Documents/BTU-PhD/troph-cost/resources_troph-cost/trophic-interactions/trophic-links_matrix_lepidoptera_plants.xlsx", sheet = "Imago_BB", na = "NA") %>%
# rename butterfly names
rename(Leptidea_sinapis_complex = Leptidea_sinapis_reali,
Melitaea_athalia = Melitaea_athalia_Komplex,
Pyrgus_alveus_complex = Pyrgus_alveus_Komplex)
## 3.4 Imago_BW (Baden-Württemberg = BW = ALB)
Imago_BW <-
readxl::read_xlsx("/Users/estebanmenaresbarraza/Documents/BTU-PhD/troph-cost/resources_troph-cost/trophic-interactions/trophic-links_matrix_lepidoptera_plants.xlsx", sheet = "Imago_BW", na = "NA") %>%
# rename butterfly names
rename(Leptidea_sinapis_complex = Leptidea_sinapis_reali,
Melitaea_athalia = Melitaea_athalia_Komplex,
Pyrgus_alveus_complex = Pyrgus_alveus_Komplex)
# check the number of plants and butterflies (dimensions without NAs)
dim_no_NA <- function(x){
x %>%
as_tibble() %>%
select(Anthocharis_cardamines:last_col()) %>%
select_if(~any(!is.na(.))) %>%
filter(!is.na(Anthocharis_cardamines)) %>%
dim()
}
dim_no_NA(Imago_BW)
dim_no_NA(Imago_BB)
dim_no_NA(Larva_BW)
dim_no_NA(Larva_BB)
# check the number of plants and butterflies (dimensions without NAs, no Zero)
dim_no_NA_no_zero <- function(x, ref_NA_row = ref_NA_row){
x %>%
as_tibble() %>%
select(all_of(ref_NA_row):last_col()) %>%
select(where( ~ any(!is.na(.)))) %>%
filter(!is.na(ref_NA_row)) %>%
select(where(~ sum(., na.rm = TRUE) > 0)) %>%
filter(rowSums(across(everything())) > 0) %>%
dim()
}
dim_no_NA_no_zero(Imago_BW, ref_NA_row = "Anthocharis_cardamines")
dim_no_NA_no_zero(Imago_BB, ref_NA_row = "Anthocharis_cardamines")
dim_no_NA_no_zero(Larva_BW, ref_NA_row = "Anthocharis_cardamines")
dim_no_NA_no_zero(Larva_BB, ref_NA_row = "Anthocharis_cardamines")
# replace any "," or "/" for ";" to avoid readability problems when exporting as csv
Larva_BB <- Larva_BB %>%
mutate(across(where(is.character), ~str_replace_all(.x, "/|,", ";")))
Larva_BW <- Larva_BW %>%
mutate(across(where(is.character), ~str_replace_all(.x, "/|,", ";")))
Imago_BB <- Imago_BB %>%
mutate(across(where(is.character), ~str_replace_all(.x, "/|,", ";")))
Imago_BW <- Imago_BW %>%
mutate(across(where(is.character), ~str_replace_all(.x, "/|,", ";")))
## ---- Save data
# Save data with wide format
write_excel_csv(Larva_BB, file = "resources_troph-cost/trophic-interactions/Larva_BB.csv")
write_excel_csv(Larva_BW, file = "resources_troph-cost/trophic-interactions/Larva_BW.csv")
write_excel_csv(Imago_BB, file = "resources_troph-cost/trophic-interactions/Imago_BB.csv")
write_excel_csv(Imago_BW, file = "resources_troph-cost/trophic-interactions/Imago_BW.csv")
# Save data with long format
Larva_BB %>%
pivot_longer(cols = Anthocharis_cardamines:last_col(),
names_to = "lepidoptera_species",
values_to = "int_strength") %>%
write_excel_csv(., file = "resources_troph-cost/trophic-interactions/Larva_BB_long.csv")
Larva_BW %>%
pivot_longer(cols = Anthocharis_cardamines:last_col(),
names_to = "lepidoptera_species",
values_to = "int_strength") %>%
write_excel_csv(., file = "resources_troph-cost/trophic-interactions/Larva_BW_long.csv")
Imago_BB %>%
pivot_longer(cols = Anthocharis_cardamines:last_col(),
names_to = "lepidoptera_species",
values_to = "int_strength") %>%
write_excel_csv(., file = "resources_troph-cost/trophic-interactions/Imago_BB_long.csv")
Imago_BW %>%
pivot_longer(cols = Anthocharis_cardamines:last_col(),
names_to = "lepidoptera_species",
values_to = "int_strength") %>%
write_excel_csv(., file = "resources_troph-cost/trophic-interactions/Imago_BW_long.csv")
# 4. MOST VISITED PLANTS --------------------------------------------------
popular_plants_SCH <- read_xlsx("data/raw/popular_plants_SCH.xlsx")
dim(popular_plants_SCH)
str(popular_plants_SCH)
# write_csv(popular_plants_SCH, file = "data/popular_plants_SCH.csv")
# 5. FLOWER AVAILABILITY ---------------------------------------------------
#' **Aim:**
#' per species and EP, calculate average of flowering units across all
#' dates and turn dataset into long format dataset: obs at each site for
#' each plant and butterfly species.
## ---- Load data
# BExIS dataset 4981 (v2) "Flower availability 2008 Alb-korrigiert"
flowers_ALB <- readxl::read_xlsx("resources_troph-cost/4981_2_FlowerAvailability_ALB-2008-OpenData/4981_2_data.xlsx")
str(flowers_ALB)
# BExIS dataset 4964 (v2) "Flower availability 2008 Schorfheide"
flowers_SCH <- readxl::read_xlsx("resources_troph-cost/4964_2_FlowerAvailability_SCH-2008-OpenData/4964_2_data.xlsx")
str(flowers_SCH)
## ---- Tidy data
# Group data per EP and plant species, and calculate mean across all dates
#ALB
flowers_ALB_filtered <- flowers_ALB %>%
group_by(EP_ID, Species, .drop = FALSE) %>%
summarise(flower_units =
mean(Flowering_unit))
#SCH
flowers_SCH_filtered <- flowers_SCH %>%
group_by(EP_ID, Species, .drop = FALSE) %>%
summarise(flower_units =
mean(Flowering_unit))
# Change variable names
#ALB
colnames(flowers_ALB_filtered)[which(
names(flowers_ALB_filtered) == "Species")] <- "plant_sp"
colnames(flowers_ALB_filtered)[which(
names(flowers_ALB_filtered) == "EP_ID")] <- "EPID"
# SCH
colnames(flowers_SCH_filtered)[which(
names(flowers_SCH_filtered) == "Species")] <- "plant_sp"
colnames(flowers_SCH_filtered)[which(
names(flowers_SCH_filtered) == "EP_ID")] <- "EPID"
# Make plant_sp names
#ALB
flowers_ALB_filtered$plant_sp <-
str_replace_all(flowers_ALB_filtered$plant_sp, " ", "_")
#SCH
flowers_SCH_filtered$plant_sp <-
str_replace_all(flowers_SCH_filtered$plant_sp, " ", "_")
# Trim empty spaces at the right side of plant_sp names
#ALB
flowers_ALB_filtered$plant_sp <-
str_trim(flowers_ALB_filtered$plant_sp, side = "right")
#SCH
flowers_SCH_filtered$plant_sp <-
str_trim(flowers_SCH_filtered$plant_sp, side = "right")
# Check unique names EPID
unique(flowers_ALB_filtered$EPID)
unique(flowers_SCH_filtered$EPID)
# Replace values of EPID
#ALB
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG1")] <- c("AEG01")
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG2")] <- c("AEG02")
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG3")] <- c("AEG03")
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG4")] <- c("AEG04")
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG6")] <- c("AEG06")
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG7")] <- c("AEG07")
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG8")] <- c("AEG08")
flowers_ALB_filtered$EPID[flowers_ALB_filtered$EPID == c("AEG9")] <- c("AEG09")
#SCH
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG1")] <- c("SEG01")
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG2")] <- c("SEG02")
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG3")] <- c("SEG03")
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG4")] <- c("SEG04")
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG6")] <- c("SEG06")
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG7")] <- c("SEG07")
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG8")] <- c("SEG08")
flowers_SCH_filtered$EPID[flowers_SCH_filtered$EPID == c("SEG9")] <- c("SEG09")
# Check unique names EPID again
unique(flowers_ALB_filtered$EPID)
unique(flowers_SCH_filtered$EPID)
# Sort dataset by EPID and plant_sp
flowers_ALB_filtered <- arrange(flowers_ALB_filtered, EPID, plant_sp)
flowers_SCH_filtered <- arrange(flowers_SCH_filtered, EPID, plant_sp)
## ---- Save data
# fwrite(flowers_ALB_filtered, file = "data/raw/flower_units_ALB.csv")
# fwrite(flowers_SCH_filtered, file = "data/raw/flower_units_SCH.csv")
# 6. FLOWER VISITATION --------------------------------------------------
## ---- Read data
# BExIS ID 10160 (v3)
flower_visitor <-
read_delim(file = "resources_troph-cost/10160_FlowerVisitorInteractions-2008-OpenData/10160_3_data.csv",
delim = ';')
str(flower_visitor)
## ---- filter only Lepidoptera species
flower_visitor <-
flower_visitor %>%
filter(Order == "Lepidoptera")
## ---- harmonize plant species names
# check names
unique(flower_visitor$Plant)
flower_visitor$Plant <-
str_replace_all(flower_visitor$Plant, " ", "_")
flower_visitor$Plant <-
str_replace_all(flower_visitor$Plant, "_ssp._orientalis", "")
flower_visitor$Plant <-
str_replace_all(flower_visitor$Plant, "_agg.", "")
flower_visitor$Plant <-
str_replace_all(flower_visitor$Plant, "_cf._", "_")
flower_visitor$Plant <-
str_trim(flower_visitor$Plant, side = "right")
# check names again
unique(flower_visitor$Plant)
## ---- harmonize lepidoptera species names
# check names
unique(flower_visitor$Species)
flower_visitor$Species <-
str_replace_all(flower_visitor$Species, " ", "_")
flower_visitor$Species <-
str_replace_all(flower_visitor$Species, "/minos_agg.", "")
flower_visitor$Species <-
str_replace_all(flower_visitor$Species, "/argyrognomon/ideas_agg.", "")
flower_visitor$Species <-
str_replace_all(flower_visitor$Species, "/argyrognomom/ideas", "")
flower_visitor$Species <-
str_replace_all(flower_visitor$Species, "_agg.", "")
flower_visitor$Species <-
str_replace_all(flower_visitor$Species, "sp.", "sp")
# check names again
unique(flower_visitor$Species)
# remove family-level observations
flower_visitor <-
flower_visitor[!grepl("_undet.", flower_visitor$Species),]
# check EP_ID names
unique(flower_visitor$EP_ID)
## ---- tidy dataset
flower_visitor <-
flower_visitor %>%
# filter out EP_IDs from region HAI
filter(
!str_detect(EP_ID, 'HEG')) %>%
# Add a leading 0 to numeric IDs to have all names with 2 digits
mutate(
EP_ID = EP_ID %>%
str_replace('(AEG|SEG)([1-9]{1})$', # create groups for regex
'\\10\\2')) %>% # add zero between groups
# arrange data
arrange(EP_ID, Plant, Species) %>%
# create a region col
mutate(
Region =
if_else(
str_detect(EP_ID, 'AEG.*') == TRUE,
'ALB',
'SCH')) %>%
distinct() %>%
# put region at the front
relocate(Region, EP_ID:Total) %>%
# rename cols
rename(plant_sp = Plant,
lepidoptera_sp = Species)
# Check if each row is a unique observation
flower_visitor %>%
distinct()
## ---- save data
# write_csv(flower_visitor, "data/raw/flower_visitation.csv", quote = "none")
# 7. RED LIST -----------------------------------------------------------
# In order to type information of red lists for each plant and lepidoptera
# species we will:
# Create a dataframe with all plant and lepidoptera species (unique
# distinct) values which have a trophic interaction AND occurr in a
# sampling site. The dataframe should consider both study regions.
# requierements
library(tidyverse)
# load data
imago_ALB <- read_csv(file = "data/imago_ALB.csv")
imago_SCH <- read_csv(file = "data/imago_SCH.csv")
# get the unique distinct names of plants and butterflies to create vectors
plants_ALB <- unique(imago_ALB$plant_sp)
lepi_ALB <- unique(imago_ALB$lepidoptera_sp)
plants_SCH <- unique(imago_SCH$plant_sp)
lepi_SCH <- unique(imago_SCH$lepidoptera_sp)
region_ALB <- rep("ALB", length(c(plants_ALB, lepi_ALB)))
region_SCH <- rep("SCH", length(c(plants_SCH, lepi_SCH)))
org_type <- c(rep("plant_sp", length(plants_ALB)),
rep("lepidoptera_sp", length(lepi_ALB)),
rep("plant_sp", length(plants_SCH)),
rep("lepidoptera_sp", length(lepi_SCH)))
# create a data frame containing all vectors
red_list <- data.frame(region = c(region_ALB,
region_SCH),
taxa = org_type,
species = c(plants_ALB,
lepi_ALB,
plants_SCH,
lepi_SCH),
red_list_detail = NA,
red_list = NA,
distribution = NA)
# save data frame
# write_csv(red_list, file = "data/raw/red_list_info.csv", quote = "none")
# Work continued in ~/scripts/wrangling/scores1_red_list.R
# 8. CROPS -----------------------------------------------------------
# variable: description
# region: study region (ALB/SCH) representing the respective state of germany (Baden-Württemberg/Brandenburg)
# crop_name: crop scientific name
# crop_group: crop grouping common name according to data provided by Rader et al. (2020) whenever a single species presented many varieties or subsp. If no group found, the same name as in crop_en
# crop_en: crop common name in english
# crop_de: crop common name in german
# UAA_2008: utilized agricultural area in year 2008
# UAA_2019: utilized agricultural area in year 2019
# mean_UAA_2015_2020: mean utilized agricultural area of a crop in hectars for years 2015-2020
# prop_area_state: proportion of a crop's mean_UAA_2015_2020 from the total state's area
# prop_area_UAA: proportion of a crop's mean_UAA_2015_2020 from the total UAA of the state
# comments: details and descriptions for each raw.
crops <-
readxl::read_excel('resources_troph-cost/crops_pollinators/crops.xlsx',
sheet = 'data',
na = 'NA') %>%
as_tibble()
crops <-
crops %>%
# round values
mutate(
UAA_2008 = round(UAA_2008, 1),
UAA_2019 = round(UAA_2019, 1),
mean_UAA_2015_2020 = round(mean_UAA_2015_2020, 1),
prop_area_state = round(prop_area_state, 5),
prop_area_UAA = round(prop_area_UAA, 5))
# write_excel_csv(crops, file = 'data/raw/crops.csv', na = 'NA')
# Work continued in script UAA_crops_regions.R...
# 9. PAIRS ---------------------------------------------------------------
# Read in data
library(tidyverse)
species <-
read_csv('data/raw/species.csv')
pairs_ALB <-
read_csv('data/raw/imago_ALB.csv')
pairs_SCH <-
read_csv('data/raw/imago_SCH.csv')
# ALB
pairs_ALB <-
pairs_ALB %>%
# separate troph_pair id into plant and butterfly id
separate(troph_pair,
into = c('plant_sp_id', 'lepi_sp_id'),
remove = TRUE) %>%
# paste id cols back to one single pair id
unite(., col = "troph_pair_id",
plant_sp_id, lepi_sp_id,
sep = "-",
remove = FALSE) %>%
# reorder cols to put troph_pair at the beginning
relocate(troph_pair_id, plant_sp:last_col())
# SCH
pairs_SCH <-
pairs_SCH %>%
# separate troph_pair id into plant and butterfly id
separate(troph_pair,
into = c('plant_sp_id', 'lepi_sp_id'),
remove = TRUE) %>%
# paste id cols back to one single pair id
unite(., col = "troph_pair_id",
plant_sp_id, lepi_sp_id,
sep = "-",
remove = FALSE) %>%
# reorder cols to put troph_pair at the beginning
relocate(troph_pair_id, plant_sp:last_col())
## ---- create a single table with all information
pairs_ALB_new <-
pairs_ALB %>%
# add a var called region
mutate(region = "ALB") %>%
# put at front
relocate(region, troph_pair_id:last_col())
pairs_SCH_new <-
pairs_SCH %>%
# add a var called region
mutate(region = "SCH") %>%
# put at front
relocate(region, troph_pair_id:last_col())
# combine tables into one called "pairs"
pairs <-
bind_rows(pairs_ALB_new, pairs_SCH_new)
# remove unnecessary tables
rm(pairs_SCH, pairs_ALB, pairs_ALB_new, pairs_SCH_new)
## ---- Check and harmonize names of pairs and species tables
# 1. Plants ALB
# get plant species of region ALB from species table
species_plant_sp <-
species %>%
filter(region == "ALB" & taxa == "plant") %>%
select(species_name) %>%
distinct() %>%
pull()
# get plant species of region ALB from pairs table
pairs_plant_sp <-
pairs %>%
filter(region == "ALB") %>%
select(plant_sp) %>%
distinct() %>%
pull()
setdiff(species_plant_sp, pairs_plant_sp)
setdiff(pairs_plant_sp, species_plant_sp)
# ALl GOOD!
# 2. Lepi ALB
# get lepi species of region ALB from species table
species_lepi_sp <-
species %>%
filter(region == "ALB" & taxa == "lepidoptera") %>%
select(species_name) %>%
distinct() %>%
pull()
# get lepi species of region ALB from pairs table
pairs_lepi_sp <-
pairs %>%
filter(region == "ALB") %>%
select(lepidoptera_sp) %>%
distinct() %>%
pull()
setdiff(species_lepi_sp, pairs_lepi_sp)
# ALL GOOD
setdiff(pairs_lepi_sp, species_lepi_sp)
# ALL GOOD
# 3. Plants SCH
# get plant species of region SCH from species table
species_plant_sp <-
species %>%
filter(region == "SCH" & taxa == "plant") %>%
select(species_name) %>%
distinct() %>%
pull()
# get plant species of region SCH from pairs table
pairs_plant_sp <-
pairs %>%
filter(region == "SCH") %>%
select(plant_sp) %>%
distinct() %>%
pull()
setdiff(species_plant_sp, pairs_plant_sp)
# no differences
setdiff(pairs_plant_sp, species_plant_sp)
# no differences
# 4. Lepi SCH
# get lepi species of region SCH from species table
species_lepi_sp <-
species %>%
filter(region == "SCH" & taxa == "lepidoptera") %>%
select(species_name) %>%
distinct() %>%
pull()
# get lepi species of region SCH from pairs table
pairs_lepi_sp <-
pairs %>%
filter(region == "SCH") %>%
select(lepidoptera_sp) %>%
distinct() %>%
pull()
setdiff(species_lepi_sp, pairs_lepi_sp)
# no differences
setdiff(pairs_lepi_sp, species_lepi_sp)
# no differences
# round non-integer values to 5 decimal places
pairs_new <- pairs %>%
mutate(
across(c(sites_plant, sites_lepi, obs_cooccur, flower_visit),
as.integer)) %>%
mutate(
across(
where(is.double), ~sprintf("%.5f", .x)))
## ---- save data
write_excel_csv(pairs_new, 'data/raw/pairs.csv', na = "NA")
# 10. SPECIES AND SCORES_SP -----------------------------------------------
# Species table: a table extracted manually with all the species names, their family, genus and name, german names, synonyms, and comments for each of the species found in the study. Species names and synonyms were checked using the Lepiforum (Rennwald and Rodeland n.d., https://lepiforum.org/) and the Global Lepidoptera Index (Beccaloni et al. 2022). Leptidea sinapis, L. reali and L. juvernica were considered as L. sinapis complex according to Dincă et al. (2011). Pyrgus alveus, P. trebevicensis, P. accrete were considered as P. alveus complex according to Tshikolovets (2011). Species names and synonyms were checked using the International Plant Names Index (IPNI 2023) and Plants of the World Online database (POWO 2023).
# Setup
library(tidyverse)
species <-
readr::read_csv('data/raw/species.csv') #%>%
# # rename var
# rename(species_name = species)
pairs <-
read_csv('data/raw/pairs.csv')
# Data tidying
## ---- Add the species id to the species table
# ALB
species_new_ALB <-
species %>%
filter(region == "ALB") %>%
select(-species_id) %>%
# add plant species id
left_join(
pairs %>%
filter(region == "ALB") %>%
select(plant_sp, plant_sp_id) %>%
distinct(),
by = c("species_name" = "plant_sp")) %>%
# add lepidoptera species id
left_join(
pairs %>%
filter(region == "ALB") %>%
select(lepidoptera_sp, lepi_sp_id) %>%
distinct(),
by = c("species_name" = "lepidoptera_sp")) %>%
# unite both cols into one
unite(., col = "species_id",
plant_sp_id, lepi_sp_id,
sep = "",
remove = TRUE,
na.rm = TRUE)
# check data ALB
plant_check <-
pairs %>%
filter(region == "ALB") %>%
select(plant_sp) %>%
distinct() %>%
pull()
plant_check_id <-
pairs %>%
filter(region == "ALB") %>%
select(plant_sp_id) %>%
distinct() %>%
pull()
lepi_check <-
pairs %>%
filter(region == "ALB") %>%
select(lepidoptera_sp) %>%
distinct() %>%
pull()
lepi_check_id <-
pairs %>%
filter(region == "ALB") %>%
select(lepi_sp_id) %>%
distinct() %>%
pull()
pairs_check <- c(plant_check, lepi_check)
pairs_check_id <- c(plant_check_id, lepi_check_id)
species_check <-
species_new_ALB %>%
filter(region == "ALB") %>%
select(species_name) %>%
distinct() %>%
pull()
species_check_id <-
species_new_ALB %>%
filter(region == "ALB") %>%
select(species_id) %>%
distinct() %>%
pull()
identical(pairs_check, species_check)
identical(pairs_check_id, species_check_id)
# SCH
species_new_SCH <-