-
Notifications
You must be signed in to change notification settings - Fork 2
/
textOut.txt
5873 lines (4882 loc) · 218 KB
/
textOut.txt
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
D:/cwrNA/src/dataPrep/addNorthAmericanCounts.r
###
# add the number of points that occur in modeling area to counts CSV and rewrite
# 20200414
###
addNorthAmericanCounts <- function(species){
# read in data filtered to north america
df1 <- spPoint@data %>%
dplyr::group_by(type) %>%
dplyr::summarise(count = n())
# if both g and h occurrences are present
if(nrow(df1) == 2){
gs <- df1 %>% filter(type=="G")
gs <- gs$count[1]
hs <- df1 %>% filter(type=="H")
hs <- hs$count[1]
}else{
# if only one or the other occurrences types area present
if(df1$type == "G"){
gs <- df1 %>% filter(type=="G")
gs <- gs$count[1]
hs <- 0
}else{
gs <- 0
hs <- df1 %>% filter(type=="H")
hs <- hs$count[1]
}
}
# read in existing counts data
df <- read.csv(paste0(sp_dir,"/counts.csv"))
# assign values
df$NA_occurrences <- nrow(spPoint)
df$NA_GUseful <- gs
df$NA_HUseful <- hs
# write out content.
write.csv(x = df, file = paste0(sp_dir,"/counts.csv"), row.names = FALSE)
}
D:/cwrNA/src/dataPrep/countryCheck.R
###
# subset all point locations that do not fall within a country of interest
# and generate the first version of clean data which is used in the modeling
# process
# 20190827
###
countryCheck <- function(species){
###
# need to join between spatial points and spatial polygon dataframe to get country information
#https://www.rdocumentation.org/packages/sp/versions/1.3-1/topics/over-methods
# create spatial point object and set CRS
# set crs to the same
xyData <<- sp::SpatialPoints(spPoint@coords)
crs(xyData) <- crs(countrySHP)
# overlay with country shp
countryVal <- data.frame(over(x = xyData, y = countrySHP)) %>%
dplyr::select(ISO_A3)
# add data back to spPoints and drop all columns that have no ISO3
spPoint@data$iso3_check <- countryVal$ISO_A3
onLand<- complete.cases(spPoint@data$iso3_check) #https://stackoverflow.com/questions/21567028/extracting-points-with-polygon-in-r
spPoint <- spPoint[onLand,]
# pull in states by taxon data and filter it to genus, species
sData <- statesData %>%
dplyr::filter(name == species)%>%
dplyr::distinct(State) %>%
dplyr::filter(State != "")
# clause for species with no state specific data in GRIN
if(nrow(sData) == 0){
cleanPoints <<- spPoint
}else{
#seperate out points that fall inside Mex, Can, and Usa
spPoint$StateTest <- spPoint@data$iso3_check %in% c("MEX", "USA", "CAN")
# we only test states for mex,usa,can. So two groups are generated here.
mucPoints <- spPoint[spPoint$StateTest == TRUE,]
nonMucPoints <- spPoint[spPoint$StateTest == FALSE,]
# filter the sp admin
if(nrow(mucPoints) > 0){
# States SP Object is a large spatial polygon feature loaded in run lineal
sSp <- statesSpObject[statesSpObject$NAME_1 %in% sData$State,]
#overlay points onto filter states data and remove any points that do not fall within know states
statePoints <- as.data.frame(over(x = mucPoints, y = sSp))%>%
dplyr::select(NAME_1)
# add data back to spPoints and drop all columns that have no ISO3
mucPoints <- mucPoints[!is.na(statePoints$NAME_1),]
t2 <- nrow(mucPoints)
#clause for when states were found to contain occurrences
if(t2 != 0){
spPoint <- rbind(mucPoints,nonMucPoints )
# filter Duplicates
uniqueP <- distinct(spPoint@data)
coords <- cbind(uniqueP$longitude, uniqueP$latitude)
# base data used in the modeling process.
cleanPoints <<- sp::SpatialPointsDataFrame(coords = coords, data = uniqueP, proj4string = crs(spPoint))
}else{
# if no occurrence data is found within the selected states this
# this process defaults back to include all data.
cleanPoints <<- spPoint
}
}else{
# if no occurrence are found in can,usa,mex the all points are kept
spPoint <- nonMucPoints
cleanPoints <<- spPoint
}
}
}
D:/cwrNA/src/dataPrep/create_sp_dirs.R
###
# Test for existing file stucture and generates sturcture if needed.
# 20200414
###
create_sp_dirs <- function(species) {
#create species dir
sp_dir <<- paste0(gap_dir,"/",genus, "/",species,"/",run_version)
if (!file.exists(sp_dir)) {dir.create(sp_dir,recursive=T)}
#create other directories
#if (!file.exists(paste(sp_dir,"/bioclim",sep=""))) {dir.create(paste(sp_dir,"/bioclim",sep=""))}
if (!file.exists(paste(sp_dir,"/gap_analysis/combined",sep=""))) {dir.create(paste(sp_dir,"/gap_analysis/combined",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/gap_analysis/exsitu",sep=""))) {dir.create(paste(sp_dir,"/gap_analysis/exsitu",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/gap_analysis/insitu",sep=""))) {dir.create(paste(sp_dir,"/gap_analysis/insitu",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/gap_analysis/redList",sep=""))) {dir.create(paste(sp_dir,"/gap_analysis/redList",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/modeling/alternatives",sep=""))) {dir.create(paste(sp_dir,"/modeling/alternatives",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/modeling/maxent",sep=""))) {dir.create(paste(sp_dir,"/modeling/maxent",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/modeling/nativeArea",sep=""))) {dir.create(paste(sp_dir,"/modeling/nativeArea",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/modeling/replicates",sep=""))) {dir.create(paste(sp_dir,"/modeling/replicates",sep=""),recursive=T)}
if (!file.exists(paste(sp_dir,"/occurrences",sep=""))) {dir.create(paste(sp_dir,"/occurrences",sep=""),recursive=T)}
#return
return(species)
}
D:/cwrNA/src/dataPrep/dataBaseTransform/botanicalGardenTransform.R
###
# reworking of botanical garden data
# 20190815
###
library(tidyverse)
library(data.table)
library(naniar)
library(reshape2)
#set base dir
base_dir <- "D:/cwrNA/occurrence_data2019_05_29/botanicalGarden"
# Load in data
csvPath <- paste0(base_dir,"/P1ABC GRIN PlantSearch match ALL.csv")
data <- data.table::fread(csvPath, header = TRUE)
# Select necessary columns from dataset
dataThin <- data %>%
select("Institution", "CollectionType",
"ParentFULLTaxon_GRIN Global_2019 final", "ParentGenus",
"ParentSpecies","ParentInfraRank", "ParentInfraEpi",
"ParentInfraRank2", "ParentInfraEpi2")
nr <- nrow(dataThin)
# construct species from species plus 4 interspecific columns
dataThin <- dataThin %>% naniar::replace_with_na(replace = list(ParentSpecies="",ParentInfraRank ="",
ParentInfraEpi="", ParentInfraRank2="",
ParentInfraEpi2="" ))
# function for testing for before concatinating species.
f = function(x){
if(!is.na(x[,7])){
x[,5] <- paste(x[,5], " ", x[,6], " ", x[,7])}
else{}
if(!is.na(x[,9])){
x[,5] <- paste(x[,5], " ", x[,6], " ", x[,7], " ", x[,8], " ", x[,9])
}
return(x)
}
t2 <- data.frame()
for(i in 1:nr){
t3 <- f(dataThin[i])
t2 <- rbind(t2,t3)
}
# define structure of the empty dataframe
df <- data.frame(taxon=character(nr),
genus=character(nr),
species=character(nr),
latitude=double(nr),
longitude=double(nr),
databaseSource=character(nr),
institutionCode=character(nr),
type=factor(nr),
uniqueID=factor(nr),
sampleCategory=character(nr),
country=character(nr),
iso3=character(nr),
localityInformation=character(nr),
biologicalStatus = character(nr),
collectionSource = character(nr),
finalOriginStat = character(nr),
stringsAsFactors=FALSE)
# assign columns to location in empty dataframe
df$taxon <- t2$`ParentFULLTaxon_GRIN Global_2019 final`
df$genus <- t2$ParentGenus
df$species <- t2$ParentSpecies
df$latitude <- NA
df$longitude <- NA
df$databaseSource <- "BotanicialGarden"
df$institutionCode <- t2$Institution
df$type <- "G"
df$uniqueID <- NA
df$sampleCategory <- t2$CollectionType
df$country <- NA
df$iso3 <- NA
df$localityInformation <- NA
df$biologicalStatus <- NA
df$collectionSource <- NA
df$finalOriginStat <- NA
# pull in checkSynomyn function and apply it
source(file="D:/cwrNA/src/dataPrep/dataBaseTransform/checkSynonymsFunction.R")
df2 <- checkSynonym(df)
# generate a list of missmatch lat long values
testLatLong <<- df2 %>%
dplyr::select(c("uniqueID","latitude", "longitude")) %>%
mutate(hasLat = !is.na(latitude) & latitude != "\\N" & latitude != "") %>%
mutate(hasLong = !is.na(longitude) & longitude != "\\N"& longitude != "") %>%
mutate(hasLatLong = hasLat & hasLong)
# pull missmatched lat long values
summariseErrors <- testLatLong %>%
filter(hasLat == TRUE & hasLong ==FALSE | hasLat == FALSE & hasLong ==TRUE)
# write out summary
print(paste0("there are ", nrow(summariseErrors)," miss matach lat long pairs."))
write.csv(x = summariseErrors, file = paste0(base_dir,"/mismatchLatLong.csv"))
# write out the new dataframe of refined data
write.csv(x = df2, file = paste0(base_dir,"/refinedBotanicalGarden.csv"))
D:/cwrNA/src/dataPrep/dataBaseTransform/capsicumTransform.R
###
# reworking of capsicum data
# 20191120
###
library(tidyverse)
library(data.table)
library(MazamaSpatialUtils)
#set base dir
base_dir <- "D:/cwrNA/occurrence_data2019_05_29/capsicum"
# Load in data
csvPath <- paste0(base_dir,"/Khoury_Capsicum_paperdata_USAspecies20191206.csv")
data <- data.table::fread(input = csvPath,header = TRUE)
# Select necessary columns from dataset
dataThin <- data %>%
dplyr::select("taxon","latitude","longitude", "db","institutioncode",
"type", "record_identifier","sampstat","collsrc", "country",
"iso2", "adm1", "adm2", "adm3", "adm4", "locality")
nr <- nrow(dataThin)
#replace iso 2 with iso 3
dataThin$iso2 <- gsub(pattern = "",replacement = NA,x = dataThin$iso2)
dataThin$iso3 <- MazamaSpatialUtils::iso2ToIso3(dataThin$iso2)
#define locality information
dataThin$local2 <- paste(dataThin$adm1,dataThin$adm2,dataThin$adm3,
dataThin$adm4, dataThin$locality,
sep=" -- ")
# define structure of the empty dataframe
df <- data.frame(taxon=character(nr),
genus=character(nr),
species=character(nr),
latitude=double(nr),
longitude=double(nr),
databaseSource=character(nr),
institutionCode=character(nr),
type=factor(nr),
uniqueID=factor(nr),
sampleCategory=character(nr),
country=character(nr),
iso3=character(nr),
localityInformation=character(nr),
biologicalStatus = character(nr),
collectionSource = character(nr),
finalOriginStat = character(nr),
stringsAsFactors=FALSE)
# assign columns to location in empty dataframe
df$taxon <- dataThin$taxon
df$genus <- "Capsicum"
df$species <- "annuum var. glabriusculum"
df$latitude <- dataThin$latitude
df$longitude <- dataThin$longitude
df$databaseSource <- "Capsicum"
df$institutionCode <- dataThin$institutioncode
df$type <- dataThin$type
df$uniqueID <- dataThin$record_identifier
df$sampleCategory <- dataThin$sampstat
df$country <- NA
df$iso3 <- dataThin$iso3
df$localityInformation <- dataThin$local2
df$biologicalStatus <- dataThin$collsrc
df$collectionSource <- NA
df$finalOriginStat <- NA
# split taxon to Genus and species
df$taxon <- gsub(pattern = "_",replacement = " ",x = df$taxon)
# write out CSV
write.csv(x= df, paste0(base_dir, "/refinedCapsicum.csv") )
D:/cwrNA/src/dataPrep/dataBaseTransform/checkSynonyms.R
####
# thin the combined data so it contains only known species of interest.
# once select, I want to rename all the synonyms to match a single taxon
# The output dataset will be something that can be used for modeling
# 20190822
###
library(tidyverse)
library(data.table)
data <- data.table::fread("D:/cwrOfNA/occurrence_data2019_05_29/combinedOccurance2019-08-29.csv", header = TRUE)
base_dir <- "D:/cwrOfNA"
# read in data and synonym list
#data <- data.table::fread(file = paste0(base_dir, "/occurrence_data2019_05_29/combinedOccurance2019-08-29.csv"), header = TRUE)
syn <- data.table::fread(file = paste0(base_dir, "/speciesList/CWRoftheUSA_synonyms.csv") ,header = TRUE)
# so the taxon/synonym sheet do not have"_" between values. I need to replace this with space
data$taxon <-gsub("_", " ", data$taxon, fixed=TRUE)
# pull data that is from the true data list.
primary <- data[data$taxon %in% unique(syn$`Taxon_GRIN Global_2019 final`),]
# create a list of unique synonyms
synList <- syn[which(syn$synonym != ""),]
synList <- unique(synList$synonym)
#Select all data where the taxon will need to be changed.
secondary <- data[data$taxon %in% synList,]
syn2 <- syn[which(syn$synonym != ""),]
# Issues with join, some species have the same synonym for mutliple taxon. There is no real way of knowing which is which
# So i think the best option is either droping those points or duplicating them? One can tell them apart by elements which
# have duplicated V1 values
### example of the join issue
syn2$syn1 <- syn2$synonym
join1 <- dplyr::left_join(x = secondary[1800:1815,], y = syn2 ,by = c("taxon" = "synonym"), keep=TRUE)
###
syn2$syn1 <- syn2$synonym
join2 <- dplyr::left_join(x = secondary, y = syn2 ,by = c("taxon" = "synonym"), keep=TRUE)
# if synonym in not NA, replace taxon with Taxon GRIN Global
join2$taxon <- join2$`Taxon_GRIN Global_2019 final`
# add step to replace genus... not sure how
### duplicate issues
issues <- join2 %>%
group_by(V1)%>%
count()%>%
filter(n != 1)
iss2 <- secondary[secondary$V1 %in% issues$V1, ]
speciecsOfIssue <- unique(iss2$taxon)
###
df1 <- dplyr::select(.data = join2,-c("Taxon_GRIN Global_2019 final","taxonomy_species_id","name","note","syn1"))
df2 <- rbind(primary, df1)
# write out the modeling data
write.csv(x = df2, file = paste0(base_dir,"/modelingData", Sys.Date(), ".csv"))
D:/cwrNA/src/dataPrep/dataBaseTransform/checkSynonymsFunction.R
####
# thin the combined data so it contains only known species of interest.
# once select, I want to rename all the synonyms to match a single taxon
# The output dataset will be something that can be used for modeling
# 20190822
###
checkSynonym <- function(data){
l1 <- ncol(data)
d1 <- read.csv("D:/cwrNA/speciesList/CWRoftheUSA_synonyms20191114.csv", header = TRUE)
syn <- d1 %>% filter(note == "synonym" )
alt <- d1 %>% filter(note == "alt name")
acp <- d1 %>% filter(note == "accepted")
# test for alt names and replace them with synonym
# join and replace
alt$alt.syn <- as.character(alt$alt.syn)
alt$synonym <- as.character(alt$synonym)
dataJoin <- dplyr::left_join(data, alt, by = c("taxon" = "alt.syn" ))
n = 0
for(i in 1:nrow(dataJoin)){
if(!is.na(dataJoin$synonym[i])){
dataJoin$taxon[i] <- dataJoin$synonym[i]
n = n+1
}
}
print(paste0(n, " number of occurences had an alt name that were replaced with a synonym"))
# drop columns from the join
dataJoin <- dataJoin[1:l1]
# test for synonym replace them with accepted names
# join and replace
syn$synonym <- as.character(syn$synonym)
syn$Taxon_GRIN.Global_2019.final <- as.character(syn$Taxon_GRIN.Global_2019.final)
dataJoin2 <- dplyr::left_join(data, syn, by = c("taxon" = "synonym" ))
n = 0
for(i in 1:nrow(dataJoin2)){
if(!is.na(dataJoin2$name[i])){
dataJoin2$taxon[i] <- dataJoin2$Taxon_GRIN.Global_2019.final[i]
n = n+1
}
}
print(paste0(n, " number of occurences had an alt name that were replaced with a synonym"))
# drop columns from the join
dataJoin2 <- dataJoin2[1:l1]
# select all rows where taxon == an acceped name
#FILTER
primary <- dataJoin2[dataJoin2$taxon %in% unique(acp$Taxon_GRIN.Global_2019.final),]
print(paste0("there were ", nrow(data)-nrow(primary) ," removed for not being accecpt crop wild relative species"))
return(primary)
}
D:/cwrNA/src/dataPrep/dataBaseTransform/combineAllDatasets.R
###
# The goal of this script is to compile all the csv from individual sources into
# a single element.
# Not sure if this is really the beset structure to work with but I'm going to try
# it and see what happens
###
library(tidyverse)
library(data.table)
base_dir <- "D:/cwrNA/occurrence_data2019_05_29"
# read in all csvs
files <- list.files(path = base_dir, pattern = ".csv",full.names = TRUE,recursive = TRUE)
# select all those that have 'refined' in the name
refined <- files[grepl(pattern = 'refined', x = files)]
# drop idigbio for now
refined <- refined[-grep(pattern = "refinedIdigBio", x = refined)]
# create an empty df with same structure
df1 <- data.frame(taxon=character(),
genus=character(),
species=character(),
latitude=double(),
longitude=double(),
databaseSource=character(),
institutionCode=character(),
type=factor(),
uniqueID=factor(),
sampleCategory=character(),
country=character(),
iso3=character(),
localityInformation=character(),
biologicalStatus = character(),
collectionSource = character(),
finalOriginStat = character(),
stringsAsFactors=FALSE)
# test for duplicates with GBIF data
# test for invalid lat long
# troubleshooting --- removing gbif from refined list
gbif <- fread(refined[grep(pattern = "refinedGBIF", x = refined)], header = TRUE)
gbif$uniqueID <- as.factor(gbif$uniqueID)
gbif <- gbif %>%dplyr::select("taxon","genus","species","latitude","longitude",
"databaseSource","institutionCode","type","uniqueID",
"sampleCategory","country","iso3","localityInformation",
"biologicalStatus", "collectionSource","finalOriginStat")
#pull capsicum and cucurbita out,
capsicum <- fread(refined[grep(pattern = "refinedCapsicum", x = refined)], header = TRUE)%>%
dplyr::select("taxon","genus","species","latitude","longitude",
"databaseSource","institutionCode","type","uniqueID",
"sampleCategory","country","iso3","localityInformation",
"biologicalStatus", "collectionSource","finalOriginStat")
cucurbita <- fread(refined[grep(pattern = "refinedCucurbita", x = refined)], header = TRUE)%>%
dplyr::select("taxon","genus","species","latitude","longitude",
"databaseSource","institutionCode","type","uniqueID",
"sampleCategory","country","iso3","localityInformation",
"biologicalStatus", "collectionSource","finalOriginStat")
refined <- refined[-grep(pattern = "refinedGBIF", x = refined)]
refined <- refined[-grep(pattern = "refinedCapsicum", x = refined)]
refined <- refined[-grep(pattern = "refinedCucurbita", x = refined)]
# create function
# read in one csv, r bind it to df, drop csv from memory
appendTable <- function(dataframe, pathToData){
data <- data.table::fread(pathToData, header = TRUE,)%>%
dplyr::select("taxon","genus","species","latitude","longitude",
"databaseSource","institutionCode","type","uniqueID",
"sampleCategory","country","iso3","localityInformation",
"biologicalStatus", "collectionSource","finalOriginStat")
dataframe <- rbind(dataframe, data)
rm(data)
return(dataframe)
}
# apply function to list of csvs
for(i in 1:length(refined)){
path <- refined[i]
df1 <- appendTable(dataframe = df1, pathToData = path)
print(paste0(path, " has been added"))
print(dim(df1))
}
# add gbif
df1 <- rbind(df1, gbif)
# remove all cucurbita and capsicum rows.
df1 <- df1[df1$genus != "Capsicum",]
df1 <- df1[df1$genus != "Cucurbita",]
# add clean capsicum and cucurbita
df1 <- rbind(df1, cucurbita,capsicum)
# read in zizania texana data
zT <- read.csv("D:/cwrNA/occurrence_data2019_05_29/zizania/Zizania_texana.csv")
# create an empty df with same structure
nr <- nrow(zT)
df2 <- data.frame(taxon=character(nr),
genus=character(nr),
species=character(nr),
latitude=double(nr),
longitude=double(nr),
databaseSource=character(nr),
institutionCode=character(nr),
type=factor(nr),
uniqueID=factor(nr),
sampleCategory=character(nr),
country=character(nr),
iso3=character(nr),
localityInformation=character(nr),
biologicalStatus = character(nr),
collectionSource = character(nr),
finalOriginStat = character(nr),
stringsAsFactors=FALSE)
# compile zazania texana to match the sctructure
df2$taxon <- "Zizania texana"
df2$genus <- "Zizania"
df2$species <- "texana"
df2$latitude <- zT$lat
df2$longitude <- zT$lon
df2$databaseSource <- zT$Source
df2$uniqueID <- zT$id
df2$type <- zT$Type
#add the addational rice data to the whole set.
df1 <- rbind(df1, df2)
# impliment taxonomic changes from Colins removal of species 20200226
# remove all species that are not being using in the CWR species list for this study from the occurrence data
sRemove <- c("Capsicum annuum", "Cucurbita okeechobeensis","Cucurbita pepo","Cucurbita pepo var. ozarkana",
"Cucurbita pepo var. texana","Persea borbonia var. borbonia","Ribes cereum var. inebrians")
#none of these species have records so, deleting them doesn't change much, still it is good for record keeping
# they were removed from the cwr_NA list csv as well.
df1 <- df1[!df1$taxon %in% sRemove,]
#convert Persea borbonia var. pubescens to Persea palustris
## pull all records
t1 <- df1 %>% filter(taxon == "Persea borbonia var. pubescens")
## convert taxon and species colums
t1$taxon <- "Persea palustris"
t1$species <- "palustris"
## remove all records from df1
df2 <- df1 %>% filter(taxon != "Persea borbonia var. pubescens")
## add new records to df1
df1 <- rbind(df2, t1)
# Convert specific species to intraspecific
## convert Vaccinium ovalifolium to Vaccinium ovalifolium var. ovalifolium
## pull all records
t1 <- df1 %>% filter(taxon == "Vaccinium ovalifolium")
## convert taxon and species colums
t1$taxon <- "Vaccinium ovalifolium var. ovalifolium"
t1$species <- "ovalifolium var. ovalifolium"
## remove all records from df1
df2 <- df1 %>% filter(taxon != "Vaccinium ovalifolium")
## add new records to df1
df1 <- rbind(df2, t1)
## convert Vaccinium erythrocarpum to Vaccinium erythrocarpum subsp. erythrocarpum
## pull all records
t1 <- df1 %>% filter(taxon == "Vaccinium erythrocarpum")
## convert taxon and species colums
t1$taxon <- "Vaccinium erythrocarpum subsp. erythrocarpum"
t1$species <- "erythrocarpum subsp. erythrocarpum"
## remove all records from df1
df2 <- df1 %>% filter(taxon != "Vaccinium erythrocarpum")
## add new records to df1
df1 <- rbind(df2, t1)
## convert Allium schoenoprasum to Allium schoenoprasum subsp. schoenoprasum
## pull all records
t1 <- df1 %>% filter(taxon == "Allium schoenoprasum")
## convert taxon and species colums
t1$taxon <- "Allium schoenoprasum subsp. schoenoprasum"
t1$species <- "schoenoprasum subsp. schoenoprasum"
## remove all records from df1
df2 <- df1 %>% filter(taxon != "Allium schoenoprasum")
## add new records to df1
df1 <- rbind(df2, t1)
## Remove all species that could have been change and replace with edits from the spreadsheet
spList <- c("Leymus salina","Leymus salina subsp. mojavensis","Leymus salina subsp. salina",
"Leymus salina subsp. salmonis","Persea borbonia","Persea borbonia var. borbonia",
"Persea borbonia var. pubescens","Saccharum brevibarbe","Saccharum brevibarbe var. brevibarbe",
"Saccharum brevibarbe var. contortum","Vaccinium crassifolium","Vaccinium crassifolium subsp. crassifolium" ,
"Vaccinium crassifolium subsp. sempervirens",'Elymus glabriflorus','Elymus glabriflorus var. australis',
'Elymus glabriflorus var. glabriflorus','Elymus glaucus','Elymus glaucus subsp. glaucus',
'Elymus glaucus subsp. mackenziei','Elymus glaucus subsp. virescens','Ipomoea cordatotriloba',
'Ipomoea cordatotriloba var. cordatotriloba','Ipomoea cordatotriloba var. torreyana',
'Juglans major','Juglans major var. major','Juglans microcarpa','Juglans microcarpa var. microcarpa',
'Leymus mollis','Leymus mollis subsp. mollis','Leymus mollis subsp. villosissimus',
'Phaseolus leptostachyus','Phaseolus leptostachyus var. leptostachyus','Prunus virginiana',
'Prunus virginiana var. demissa','Prunus virginiana var. virginiana','Ribes cereum',
'Ribes cereum var. cereum','Ribes cereum var. colubrinum','Rubus ursinus',
'Rubus ursinus subsp. macropetalus','Rubus ursinus subsp. ursinus','Tripsacum dactyloides',
'Tripsacum dactyloides var. dactyloides'
)
## select all species that are not in the list
t1 <- df1 %>% filter(!taxon %in% spList)
## read in and join altered taxon lists
t2 <- read.csv("D:/cwrNA/parameters/USA_cropWildRelativeInventory/intraspecificAlterations/intraSpecificSpecsNewTaxonEdits.csv")
t3 <- read.csv("D:/cwrNA/parameters/USA_cropWildRelativeInventory/intraspecificAlterations/intraSpecificSpecsList2NewTaxonEdits.csv")
t4 <- rbind(t2, t3)
###**there is 11 more occurrence in this re combined dataset... I don't know exactly why that is
# I'm rolling with it for now
df2 <- rbind(t1, t4)
# redefine genus and species to account for the duplication of values
df3 <- df2 %>%
dplyr::mutate(t0 = taxon)%>%
tidyr::separate(col = t0,into = c("t1","t2", "t3","t4","t5","t6"),
sep = " ")
df3$genus <- df3$t1
df4 <- df3[,18:22]
# was assigning this to a column in a second dataframe and it was causeing quite a few issues.
# keep it seperate seemed to fix the issues.
df4 <- df4 %>% tidyr::unite("z", na.rm = TRUE , sep = " ")
df3$species <- df4$z
df2a <- df3[,1:16]
# colnames(df2) <- c("taxon","genus" ,
# "species","latitude",
# "longitude","databaseSource","institutionCode","type","uniqueID","sampleCategory",
# "country","iso3", "localityInformation", "biologicalStatus","collectionSource",
# "finalOriginStat")
# write out final csv
write.csv(x = df2a, file = paste0(base_dir,"/combinedOccurance", Sys.Date(), ".csv"))
D:/cwrNA/src/dataPrep/dataBaseTransform/cucurbitaTransform.R
###
# reworking of cucurbita data
# 20191120
###
library(tidyverse)
library(data.table)
#set base dir
base_dir <- "D:/cwrNA/occurrence_data2019_05_29/cucurbita"
# Load in data
csvPath <- paste0(base_dir,"/Khoury_Cucurbita_paperdata_USAspecies20191206.csv")
data <- data.table::fread(input = csvPath,header = TRUE)
# Select necessary columns from dataset
dataThin <- data
nr <- nrow(dataThin)
# define structure of the empty dataframe
df <- data.frame(taxon=character(nr),
genus=character(nr),
species=character(nr),
latitude=double(nr),
longitude=double(nr),
databaseSource=character(nr),
institutionCode=character(nr),
type=factor(nr),
uniqueID=factor(nr),
sampleCategory=character(nr),
country=character(nr),
iso3=character(nr),
localityInformation=character(nr),
biologicalStatus = character(nr),
collectionSource = character(nr),
finalOriginStat = character(nr),
stringsAsFactors=FALSE)
# assign columns to location in empty dataframe
df$taxon <- dataThin$taxon
df$genus <- "Cucurbita"
df$species <- NA
df$latitude <- dataThin$latitude
df$longitude <- dataThin$longitude
df$databaseSource <- "cucurbita"
df$institutionCode <- dataThin$institute
df$type <- dataThin$type
df$uniqueID <- dataThin$sample_number
df$sampleCategory <- dataThin$status
df$country <- dataThin$country
df$iso3 <- NA
df$localityInformation <- dataThin$locality
df$biologicalStatus <- NA
df$collectionSource <- NA
df$finalOriginStat <- NA
# split taxon into genus and species
df$taxon <- gsub(pattern = "_", replacement = " ", x = df$taxon)
df$species <- gsub(pattern = "Cucurbita", replacement = "", x = df$taxon)
#write CSV
write.csv(x = df, file = paste0(base_dir, "/refinedCucurbita.csv"))
D:/cwrNA/src/dataPrep/dataBaseTransform/cwrOfNorthAmericaTransfom.R
###
# reworking of botanical garden data
# 20190815
###
library(tidyverse)
library(data.table)
#set base dir
base_dir <- "D:/cwrNA/occurrence_data2019_05_29/cwrofnorthamericabook"
# Load in data
csvPath <- paste0(base_dir,"/CWRofNAmerica_dataextras.csv")
data <- data.table::fread(csvPath, header = TRUE)
# Select necessary columns from dataset
dataThin <- data %>%
select("id", "Taxon","Type","Source",
"lat", "lon", "final_cult_stat")
nr <- nrow(dataThin)
# define structure of the empty dataframe
df <- data.frame(taxon=character(nr),
genus=character(nr),
species=character(nr),
latitude=double(nr),
longitude=double(nr),
databaseSource=character(nr),
institutionCode=character(nr),
type=factor(nr),
uniqueID=factor(nr),
sampleCategory=character(nr),
country=character(nr),
iso3=character(nr),
localityInformation=character(nr),
biologicalStatus = character(nr),
collectionSource = character(nr),
finalOriginStat = character(nr),
stringsAsFactors=FALSE)
# assign columns to location in empty dataframe
df$taxon <- dataThin$Taxon
df$genus <- NA
df$species <- NA
df$latitude <- dataThin$lat
df$longitude <- dataThin$lon
df$databaseSource <- "cwrofnorthamericabook"
df$institutionCode <- dataThin$Source
df$type <- dataThin$Type
df$uniqueID <- dataThin$id
df$sampleCategory <- NA
df$country <- NA
df$iso3 <- NA
df$localityInformation <- NA
df$biologicalStatus <- dataThin$final_cult_stat
df$collectionSource <- NA
df$finalOriginStat <- NA
# determine Genus and species from taxon
test1 <- tidyr::separate(data = df,taxon,into=c("genus","species","sep1","var1"),sep="_")
#create new column to populate
test1$fullSpecies <- NA
for(i in 1:nrow(test1)){
if(is.na(test1$var1[i])){
test1$fullSpecies[i] <- test1$species[i]
}
if(!is.na(test1$var1[i])){
test1$fullSpecies[i] <- paste(test1$species[i],test1$sep1[i],test1$var1[i], sep="_")
}
}
#set genus and species in final DF
df$genus <- test1$genus
df$species <- test1$fullSpecies
# replace _ with " " on taxon
df$taxon <- gsub(pattern = "_", replacement = " ",x = df$taxon)
# pull in checkSynomyn function and apply it
source(file="D:/cwrNA/src/dataPrep/dataBaseTransform/checkSynonymsFunction.R")
df <- checkSynonym(df)
# actual code
testLatLong <<- df %>%
dplyr::select(c("uniqueID","latitude", "longitude")) %>%
mutate(hasLat = !is.na(latitude) & latitude != "\\N" & latitude != "") %>%
mutate(hasLong = !is.na(longitude) & longitude != "\\N"& longitude != "") %>%
mutate(hasLatLong = hasLat & hasLong)
summariseErrors <- testLatLong %>%
filter(hasLat == TRUE & hasLong ==FALSE | hasLat == FALSE & hasLong ==TRUE)
print(paste0("there are ", nrow(summariseErrors)," miss matach lat long pairs."))
write.csv(x = summariseErrors, file = paste0(base_dir,"/mismatchLatLong.csv"))
# write out the new dataframe
write.csv(x = df, file = paste0(base_dir,"/refinedcwrOfNABook.csv"))
D:/cwrNA/src/dataPrep/dataBaseTransform/cwrTransform.R
###
# reworking of wiews data
# 20190815
###
library(tidyverse)
library(data.table)
#set base dir
base_dir <- "D:/cwrNA/occurrence_data2019_05_29/cwr_occ/20191114"
# Load in data
csvPath <- paste0(base_dir,"/colin_dan_data.csv")
data <- data.table::fread(csvPath, header = TRUE)
d1 <- head(data)
#filter by filename
exclude <- read.csv(file = "D:/cwrNA/occurrence_data2019_05_29/cwr_occ/ExcludefromCWROCC.csv", header=TRUE) %>%
filter(Exclude == "Y")
listExclude<- c("GBIF","raw_ATGGC_ff.xlsx","raw_AVRDC_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_1a_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_1b_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_1c_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_1d_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_1e_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_2a_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_2b_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_2c_ff.xlsx",
"raw_Bioversity_EUR_SING_2013_2d_ff.xlsx",
"raw_CATIE_2014_ff.xlsx",
"raw_CK_USDA_NPGS_GRIN_USCWR.xlsx",
"raw_Helianthus_Marek_newdata_ff",
"raw_IRRI_newdata_ff.xlsx",
"raw_USCWRExtras_CS_FF.xlsx",
"raw_USDA_NPGS_GRIN_extras_ff.xlsx",
"raw_USDA_NPGS_GRIN_FF.xlsx",
"raw_USDA_NPGS_GRIN_Hijmans_ff.xlsx")
data <- data[!data$filename %in% listExclude,]
#View(data)
dim(data)
# Select necessary columns from dataset
dataThin <- data %>%
dplyr::select("id","source","provider_institute_id","f_x1_genus","f_x1_sp1","taxstand_final_taxon",
"final_lon", "final_lat", "adm1", "adm2", "adm3", "adm4", "locality", "cultivated")
nr <- nrow(dataThin)
# filter by final cult status- not "cultivated"
dataThin <- dataThin[!dataThin$final_cult_stat %in% c("cultivated"),]
dim(dataThin)
# define structure of the empty dataframe
df <- data.frame(taxon=character(nr),
genus=character(nr),
species=character(nr),
latitude=double(nr),
longitude=double(nr),
databaseSource=character(nr),
institutionCode=character(nr),
type=factor(nr),
uniqueID=factor(nr),
sampleCategory=character(nr),
country=character(nr),
iso3=character(nr),
localityInformation=character(nr),
stringsAsFactors=FALSE)
# assign columns to location in empty dataframe
df$taxon <- dataThin$taxstand_final_taxon
df$genus <- dataThin$f_x1_genus
df$species <- NA
df$latitude <- dataThin$final_lat
df$longitude <- dataThin$final_lon
df$databaseSource <- "cwr_occ"
df$institutionCode <- dataThin$provider_institute_id
df$type <- dataThin$source
df$uniqueID <- dataThin$id
df$sampleCategory <- NA
df$country <- NA
df$iso3 <- NA
df$localityInformation <- dataThin$locality
df$biologicalStatus <- NA
df$collectionSource <- NA
df$finalOriginStat <- NA
# Spilt name to get at genus and species
#test <- df[1:100,]
df$name <- df$taxon
df <- tidyr::separate(data = df, "name",into =c('genus1','spec','sub1','sub2','sub3'),sep='_')
#View(df[1:1000,])
# for what ever reason the first clause of this funtion is not working. I'm leaving it for now because
# I dont think we actaully need a acurate species to do the analysis
##
#View(df4[1:1000,])
# remove all NA
df6 <- str_replace_all(df$taxon, pattern = "_", replacement = " " )
#View(df6)
df$taxon <- df6