-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0.0_Functions_Estimating_Impacts_18Feb2022.R
2089 lines (1822 loc) · 105 KB
/
0.0_Functions_Estimating_Impacts_18Feb2022.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
# Functions for estimating env impacts and nutriscore for each product
###
# Getting nutritional units, and adjusting all values to g/100g
# With the exception of energy, which will be kj/100g
nutrition.adjust.function <-
function(dat, nutrient.list) {
# Creating new columns to store data
dat[,paste0(nutrient.list,"_value")] <- NA
dat[,paste0(nutrient.list,"_unit")] <- NA
dat <- as.data.frame(dat)
dat$tmp.check <- NA
# Looping through columns
for(nutrient in nutrient.list) {
# Extracting numbers and decimals
# Do this in two steps
# (1) Extracting numeric values
dat[grep(".",dat[,paste0(nutrient)]),paste0(nutrient,"_value")] <-
str_extract(dat[grep(".",dat[,paste0(nutrient)]),nutrient],
"[0-9]{1,4}(\\s)?.(\\s)?[0-9]{1,3}|[0-9]{1,4}|
[0-9]{1,4}(\\s)?,(\\s)?[0-9]{1,3}")
# Trimming white space
dat[,paste0(nutrient,"_value")] <-
gsub("[[:space:]]", "", dat[,paste0(nutrient,"_value")])
# Converting to numeric
dat[,paste0(nutrient,"_value")] <-
as.numeric(dat[,paste0(nutrient,"_value")])
# Extracting unit
dat[,paste0(nutrient,"_unit")] <-
str_extract(dat[,nutrient],
"mg|g|kcal|calorie|kj|j|kiloj")
# Adjusting units
dat[paste0(nutrient,"_unit") %in% 'kcal',paste0(nutrient,"_value")] <-
dat[paste0(nutrient,"_unit") %in% 'kcal',paste0(nutrient,"_value")] * 4.184
dat[paste0(nutrient,"_unit") %in% 'mg',paste0(nutrient,"_value")] <-
dat[paste0(nutrient,"_unit") %in% 'mg',paste0(nutrient,"_value")] / 1000
# And correcting
if(nutrient %in% c('Energy_pack')) {
dat[(dat$Energy_pack_unit %in% c('g','mg')),'tmp.check'] <-
1
} else if (nutrient %in% c('Sodium_pack')) {
dat[dat$Sodium_pack_unit %in% c('mg'),'Sodium_pack_value'] <-
dat[dat$Sodium_pack_unit %in% c('mg'),'Sodium_pack_value'] / 1000
dat[dat$Sodium_pack_unit %in% c('mg'),'unit'] <-
'g'
dat[!(dat[,'Sodium_pack_unit'] %in% c('g')),'tmp.check'] <-
1
} else {
dat[dat[,paste0(nutrient,"_unit")] %in% 'mg',paste0(nutrient,"_value")] <-
dat[dat[,paste0(nutrient,"_unit")] %in% 'mg',paste0(nutrient,"_value")] / 1000
dat[dat[,paste0(nutrient,"_unit")] %in% 'mg',paste0(nutrient,"_unit")] <-
'g'
dat[!(dat[,paste0(nutrient,"_unit")] %in% 'g'),'tmp.check'] <-
1
}
dat[!is.na(dat$tmp.check),paste0(nutrient,"_value")] <- NA
dat$tmp.check <- NA
}
# Updating values
return(dat)
}
###
# Function to calculate nutriscore
#####
###
# Calculating nutriscore
nutriscore.function = function(dat) {
nutriscore.solid <-
dat %>%
mutate(Calories = ifelse(is.na(Calories), 0, Calories),
Protein = ifelse(is.na(Protein), 0, Protein),
Fat = ifelse(is.na(Fat), 0, Fat),
SaturatedFat = ifelse(is.na(SaturatedFat), 0, SaturatedFat),
Fiber = ifelse(is.na(Fiber), 0, Fiber),
Sodium = ifelse(is.na(Sodium), 0, Sodium),
Sugar = ifelse(is.na(Sugar), 0, Sugar),
FVNO = ifelse(is.na(FVNO), 0, FVNO)) %>%
mutate(tot_nutrition = Calories + Protein + Fat + SaturatedFat + Fiber + Sodium + Sugar) %>%
mutate(NutriCal = ifelse(Calories * 4.184 > 3350, 10, # Getting cutoffs for ingredients included in nutriscore calculations
ifelse(Calories * 4.184 > 3015, 9,
ifelse(Calories * 4.184 > 2680, 8,
ifelse(Calories * 4.184 > 2345, 7,
ifelse(Calories * 4.184 > 2010, 6,
ifelse(Calories * 4.184 > 1675, 5,
ifelse(Calories * 4.184 > 1340, 4,
ifelse(Calories * 4.184 > 1005, 3,
ifelse(Calories * 4.184 > 670, 2,
ifelse(Calories * 4.184 > 335, 1,0))))))))))) %>%
mutate(NutriSugar = ifelse(Sugar > 45, 10,
ifelse(Sugar>40, 9,
ifelse(Sugar>36,8,
ifelse(Sugar>31,7,
ifelse(Sugar>27,6,
ifelse(Sugar>22.5,5,
ifelse(Sugar>18,4,
ifelse(Sugar>13.5,3,
ifelse(Sugar>9,2,
ifelse(Sugar>4.5,1,0))))))))))) %>%
mutate(NutriSatFats = ifelse(SaturatedFat > 10, 10,
ifelse(SaturatedFat > 9, 9,
ifelse(SaturatedFat > 8, 8,
ifelse(SaturatedFat > 7, 7,
ifelse(SaturatedFat > 6, 6,
ifelse(SaturatedFat > 5, 5,
ifelse(SaturatedFat > 4, 4,
ifelse(SaturatedFat > 3, 3,
ifelse(SaturatedFat > 2, 2,
ifelse(SaturatedFat > 1, 1,0))))))))))) %>%
mutate(NutriSodium = ifelse(Sodium > 900,10,
ifelse(Sodium > 810, 9,
ifelse(Sodium > 720, 8,
ifelse(Sodium > 630, 7,
ifelse(Sodium > 540, 6,
ifelse(Sodium > 450, 5,
ifelse(Sodium > 360, 4,
ifelse(Sodium > 270, 3,
ifelse(Sodium > 180, 2,
ifelse(Sodium > 90, 1, 0))))))))))) %>%
mutate(NutriFatRatio = SaturatedFat / Fat) %>% # Oils calculated based on ratio of sat fat : fat
mutate(NutriFatRatioScore = ifelse(NutriFatRatio < .1, 0,
ifelse(NutriFatRatio < .16, 1,
ifelse(NutriFatRatio < .22, 2,
ifelse(NutriFatRatio < .28, 3,
ifelse(NutriFatRatio < .34, 4,
ifelse(NutriFatRatio < .4, 5,
ifelse(NutriFatRatio < .46, 6,
ifelse(NutriFatRatio < .52, 7,
ifelse(NutriFatRatio < .58, 8,
ifelse(NutriFatRatio < .64, 9, 10))))))))))) %>%
mutate(NutriFVNO = ifelse(FVNO > 80, 5,
ifelse(FVNO > 60, 2,
ifelse(FVNO > 40, 1, 0)))) %>%
mutate(NutriFiber = ifelse(Fiber > 3.5, 5,
ifelse(Fiber > 2.8, 4,
ifelse(Fiber > 2.1, 3,
ifelse(Fiber > 1.4, 2,
ifelse(Fiber > .7, 1, 0)))))) %>%
mutate(NutriProtein = ifelse(Protein > 8, 5,
ifelse(Protein > 6.4, 4,
ifelse(Protein > 4.8, 3,
ifelse(Protein > 3.2, 2,
ifelse(Protein > 1.6, 1, 0)))))) %>%
mutate(NutriScoreNeg = NutriCal + NutriSugar + NutriSatFats + NutriSodium) %>% # Calculating negative and positive points
mutate(NutriScorePos = NutriFiber + NutriFVNO + NutriProtein) %>%
mutate(NutriScorePoints = NutriScoreNeg - NutriScorePos) %>% # Calculating nutriscore for general products
mutate(NutriScorePoints = ifelse(NutriScoreNeg >= 11 & NutriFVNO < 5, NutriScoreNeg - (NutriFiber + NutriFVNO), NutriScorePoints)) %>% # Exception for products with negative value >= 11
mutate(NutriScorePoints = ifelse(cheese %in% 'Cheese',NutriScoreNeg - NutriScorePos, NutriScorePoints)) %>% # Exception for cheese
mutate(NutriScorePoints = ifelse(fat.oil %in% 'Fats.Oils', NutriCal + NutriSugar + NutriFatRatioScore + NutriSodium - (NutriFiber + NutriProtein), NutriScorePoints)) %>% # Exception for added fats
mutate(NutriScoreLetter = # Calculating nutriscore
ifelse(NutriScorePoints <= -1, 'A',
ifelse(NutriScorePoints <= 2, 'B',
ifelse(NutriScorePoints <= 10, 'C',
ifelse(NutriScorePoints <= 18, 'D',
ifelse(NutriScorePoints >= 19, 'E',NA)))))) %>%
mutate(NutriScore_Scaled = (NutriScorePoints + 15) / 55) %>% # Scaling to range from 0 to 1 (0 = best, 1 = worst)
filter(drinks %in% 'No')
nutriscore.drinks <-
dat %>%
mutate(Calories = ifelse(is.na(Calories), 0, Calories),
Protein = ifelse(is.na(Protein), 0, Protein),
Fat = ifelse(is.na(Fat), 0, Fat),
SaturatedFat = ifelse(is.na(SaturatedFat), 0, SaturatedFat),
Fiber = ifelse(is.na(Fiber), 0, Fiber),
Sodium = ifelse(is.na(Sodium), 0, Sodium),
Sugar = ifelse(is.na(Sugar), 0, Sugar),
FVNO = ifelse(is.na(FVNO), 0, FVNO)) %>%
mutate(tot_nutrition = Calories + Protein + Fat + SaturatedFat + Fiber + Sodium + Sugar) %>%
mutate(NutriCal = ifelse(Calories * 4.184 > 270, 10, # Getting cutoffs for ingredients included in nutriscore calculations
ifelse(Calories * 4.184 > 240, 9,
ifelse(Calories * 4.184 > 210, 8,
ifelse(Calories * 4.184 > 180, 7,
ifelse(Calories * 4.184 > 150, 6,
ifelse(Calories * 4.184 > 120, 5,
ifelse(Calories * 4.184 > 90, 4,
ifelse(Calories * 4.184 > 60, 3,
ifelse(Calories * 4.184 > 30, 2,
ifelse(Calories * 4.184 > 0, 1,0))))))))))) %>%
mutate(NutriSugar = ifelse(Sugar > 13.5, 10,
ifelse(Sugar>12, 9,
ifelse(Sugar>10.5,8,
ifelse(Sugar>9,7,
ifelse(Sugar>7.5,6,
ifelse(Sugar>6,5,
ifelse(Sugar>4.5,4,
ifelse(Sugar>3,3,
ifelse(Sugar>1.5,2,
ifelse(Sugar>0,1,0))))))))))) %>%
mutate(NutriSatFats = ifelse(SaturatedFat > 10, 10,
ifelse(SaturatedFat > 9, 9,
ifelse(SaturatedFat > 8, 8,
ifelse(SaturatedFat > 7, 7,
ifelse(SaturatedFat > 6, 6,
ifelse(SaturatedFat > 5, 5,
ifelse(SaturatedFat > 4, 4,
ifelse(SaturatedFat > 3, 3,
ifelse(SaturatedFat > 2, 2,
ifelse(SaturatedFat > 1, 1,0))))))))))) %>%
mutate(NutriSodium = ifelse(Sodium > 900,10,
ifelse(Sodium > 810, 9,
ifelse(Sodium > 720, 8,
ifelse(Sodium > 630, 7,
ifelse(Sodium > 540, 6,
ifelse(Sodium > 450, 5,
ifelse(Sodium > 360, 4,
ifelse(Sodium > 270, 3,
ifelse(Sodium > 180, 2,
ifelse(Sodium > 90, 1, 0))))))))))) %>%
mutate(NutriFatRatio = SaturatedFat / Fat) %>% # Oils calculated based on ratio of sat fat : fat
mutate(NutriFatRatioScore = ifelse(NutriFatRatio < .1, 0,
ifelse(NutriFatRatio < .16, 1,
ifelse(NutriFatRatio < .22, 2,
ifelse(NutriFatRatio < .28, 3,
ifelse(NutriFatRatio < .34, 4,
ifelse(NutriFatRatio < .4, 5,
ifelse(NutriFatRatio < .46, 6,
ifelse(NutriFatRatio < .52, 7,
ifelse(NutriFatRatio < .58, 8,
ifelse(NutriFatRatio < .64, 9, 10))))))))))) %>%
mutate(NutriFVNO = ifelse(FVNO > 80, 10,
ifelse(FVNO > 60, 4,
ifelse(FVNO > 40, 2, 0)))) %>%
mutate(NutriFiber = ifelse(Fiber > 4.7, 5,
ifelse(Fiber > 3.7, 4,
ifelse(Fiber > 2.8, 3,
ifelse(Fiber > 1.9, 2,
ifelse(Fiber > .9, 1, 0)))))) %>%
mutate(NutriProtein = ifelse(Protein > 8, 5,
ifelse(Protein > 6.4, 4,
ifelse(Protein > 4.8, 3,
ifelse(Protein > 3.2, 2,
ifelse(Protein > 1.6, 1, 0)))))) %>%
mutate(NutriScoreNeg = NutriCal + NutriSugar + NutriSatFats + NutriSodium) %>% # Calculating negative and positive points
mutate(NutriScorePos = NutriFiber + NutriFVNO + NutriProtein) %>%
mutate(NutriScorePoints = NutriScoreNeg - NutriScorePos) %>% # Calculating nutriscore for general products
mutate(NutriScorePoints = ifelse(NutriScoreNeg >= 11 & NutriFVNO < 5, NutriScoreNeg - (NutriFiber + NutriFVNO), NutriScorePoints)) %>% # Exception for products with negative value >= 11
mutate(NutriScoreLetter = # Calculating nutriscore
ifelse(NutriScorePoints <= -20, 'B',
ifelse(NutriScorePoints <= 1, 'B',
ifelse(NutriScorePoints <= 5, 'C',
ifelse(NutriScorePoints <= 9, 'D',
ifelse(NutriScorePoints >= 10, 'E', NA)))))) %>%
mutate(NutriScore_Scaled = (NutriScorePoints + 15) / 55) %>% # Scaling to range from 0 to 1 (0 = best, 1 = worst)
filter(drinks %in% 'Drinks') %>%
mutate(NutriScoreLetter = ifelse(grepl('Water',product_name,ignore.case = TRUE),'A',NutriScoreLetter))
# Binding
nutriscore <-
rbind(nutriscore.solid,
nutriscore.drinks)
return(nutriscore)
}
###
# Env estimate function
env.estimate.function = function(dat,
lca.dat) {
# And taking summary by product id
dat <-
left_join(dat,
lca.dat) %>%
mutate(GHGs = GHG / 10 * percent / 100, # Calculating impacts
Land = Land / 10 * percent / 100,
Eut = Eut / 10 * percent / 100,
WatScar = WatScar / 10 * percent / 100) %>%
group_by(id, product_name, Retailer, Department, Aisle, Shelf) %>%
summarise(GHGs_100g = sum(GHGs, na.rm = TRUE), # Impacts by product, retailer, department, etc
Land_100g = sum(Land, na.rm = TRUE),
Eut_100g = sum(Eut, na.rm = TRUE),
WatScar_100g = sum(WatScar, na.rm = TRUE))
# Returning data set
return(dat)
}
env.scaling.function =
function(dat, env.indicators) {
# Listed of scaled names
cols.loops <- names(dat)[grep(env.indicators, names(dat))]
scaled.names <- paste0('scaled_', cols.loops)
# Looping through these to scale from 0 (no impact) to 100 (highest impact)
for(i in 1:length(cols.loops)) {
# Scaling from 0 to 1
dat[,scaled.names[i]] <-
dat[,cols.loops[i]] / max(dat[,cols.loops[i]], na.rm = TRUE)
# Scaling from 0 to 100
dat[,scaled.names[i]] <- dat[,scaled.names[i]] * 100
}
# Returning data set
return(dat)
}
# scaling.function =
# function(dat, env.indicators) {
# # Listed of scaled names
# cols.loops <- names(dat)[grep(env.indicators, names(dat))]
# scaled.names <- paste0('scaled_', cols.loops)
#
# # Looping through these to scale from 0 (no impact) to 100 (highest impact)
# for(i in 1:length(cols.loops)) {
# # Scaling from 0 to 1
# dat[,scaled.names[i]] <-
# dat[,cols.loops[i]] / max(dat[,gsub("[^serving_].*_","mean_",cols.loops[i])], na.rm = TRUE)
# # Scaling from 0 to 100
# dat[,scaled.names[i]] <- dat[,scaled.names[i]] * 100
# }
#
# # And scaling nutriscore
# dat[,'NutriScore_Scaled'] <-
# (dat[,'NutriScorePoints'] + abs(min(dat[,'NutriScorePoints'], na.rm = TRUE))) /
# (max(dat[,'NutriScorePoints'], na.rm = TRUE) + abs(min(dat[,'NutriScorePoints'], na.rm = TRUE)))
#
# dat[,'NutriScore_Scaled'] <- dat[,'NutriScore_Scaled'] * 100
#
# # And getting tot env scaled for 100g and for serving
# dat[,'Tot_env_serving_scaled_lower_ci'] <-
# (rowSums(dat[,names(dat)[grep('scaled_serving_lower',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_serving_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_serving_scaled_upper_ci'] <-
# (rowSums(dat[,names(dat)[grep('scaled_serving_upper',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_serving_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_serving_min'] <-
# (rowSums(dat[,names(dat)[grep('scaled_serving_min',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_serving_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_serving_max'] <-
# (rowSums(dat[,names(dat)[grep('scaled_serving_max',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_serving_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_serving_scaled'] <-
# (rowSums(dat[,names(dat)[grep('scaled_serving_mean',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_serving_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_100g_scaled_lower_ci'] <-
# (rowSums(dat[,names(dat)[grep('scaled_lower',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_100g_scaled_upper_ci'] <-
# (rowSums(dat[,names(dat)[grep('scaled_upper',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_100g_scaled_min'] <-
# (rowSums(dat[,names(dat)[grep('scaled_min',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_100g_scaled_max'] <-
# (rowSums(dat[,names(dat)[grep('scaled_max',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_mean',names(dat))]]), na.rm = TRUE)) * 100
#
# dat[,'Tot_env_100g_scaled'] <-
# (rowSums(dat[,names(dat)[grep('scaled_mean',names(dat))]]) /
# max(rowSums(dat[,names(dat)[grep('scaled_mean',names(dat))]]), na.rm = TRUE)) * 100
#
#
# # Returning data set
# return(dat)
# }
scaling.function <-
function(dat, env.indicators) {
# Listed of scaled names
cols.loops <- names(dat)[grep(env.indicators, names(dat))]
scaled.names <- paste0('scaled_', cols.loops)
# Looping through these to scale from 0 (no impact) to 100 (highest impact)
for(i in 1:length(cols.loops)) {
# Scaling from 0 to 1
dat[,scaled.names[i]] <-
dat[,cols.loops[i]] / max(dat[,gsub("[^serving_].*_","mean_",cols.loops[i])], na.rm = TRUE)
# Scaling from 0 to 100
dat[,scaled.names[i]] <- dat[,scaled.names[i]] * 100
}
# And scaling nutriscore
dat[,'NutriScore_Scaled'] <-
(dat[,'NutriScorePoints'] + abs(min(dat[,'NutriScorePoints'], na.rm = TRUE))) /
(max(dat[,'NutriScorePoints'], na.rm = TRUE) + abs(min(dat[,'NutriScorePoints'], na.rm = TRUE)))
dat[,'NutriScore_Scaled'] <- dat[,'NutriScore_Scaled'] * 100
# And udpating the rest for env
dat <-
dat %>%
mutate(Tot_env_serving_scaled_lower_ci = (scaled_serving_lower_ci_GHG + scaled_serving_lower_ci_Eut + scaled_serving_lower_ci_Land + scaled_serving_lower_ci_WatScar)/4,
Tot_env_serving_scaled_upper_ci = (scaled_serving_upper_ci_GHG + scaled_serving_upper_ci_Eut + scaled_serving_upper_ci_Land + scaled_serving_upper_ci_WatScar)/4,
Tot_env_serving_scaled_min = (scaled_serving_min_GHG + scaled_serving_min_Eut + scaled_serving_min_Land + scaled_serving_min_WatScar)/4,
Tot_env_serving_scaled_max = (scaled_serving_max_GHG + scaled_serving_max_Eut + scaled_serving_max_Land + scaled_serving_max_WatScar)/4,
Tot_env_serving_scaled_lower_fifth = (scaled_serving_lower_fifth_GHG + scaled_serving_lower_fifth_Eut + scaled_serving_lower_fifth_Land + scaled_serving_lower_fifth_WatScar)/4,
Tot_env_serving_scaled_upper_ninetyfifth = (scaled_serving_upper_ninetyfifth_GHG + scaled_serving_upper_ninetyfifth_Eut + scaled_serving_upper_ninetyfifth_Land + scaled_serving_upper_ninetyfifth_WatScar)/4,
Tot_env_serving_scaled = (scaled_serving_mean_GHG + scaled_serving_mean_Eut + scaled_serving_mean_Land + scaled_serving_mean_WatScar)/4) %>%
mutate(Tot_env_serving_scaled_lower_ci = Tot_env_serving_scaled_lower_ci / max(Tot_env_serving_scaled, na.rm = TRUE) * 100,
Tot_env_serving_scaled_upper_ci = Tot_env_serving_scaled_upper_ci / max(Tot_env_serving_scaled, na.rm = TRUE) * 100,
Tot_env_serving_scaled_min = Tot_env_serving_scaled_min / max(Tot_env_serving_scaled, na.rm = TRUE) * 100,
Tot_env_serving_scaled_max = Tot_env_serving_scaled_max / max(Tot_env_serving_scaled, na.rm = TRUE) * 100,
Tot_env_serving_scaled_lower_fifth = Tot_env_serving_scaled_lower_fifth / max(Tot_env_serving_scaled, na.rm = TRUE) * 100,
Tot_env_serving_scaled_upper_ninetyfifth = Tot_env_serving_scaled_upper_ninetyfifth / max(Tot_env_serving_scaled, na.rm = TRUE) * 100,
Tot_env_serving_scaled = Tot_env_serving_scaled / max(Tot_env_serving_scaled, na.rm = TRUE) * 100) %>%
mutate(Tot_env_100g_scaled_lower_ci = (scaled_lower_ci_GHG + scaled_lower_ci_Eut + scaled_lower_ci_Land + scaled_lower_ci_WatScar)/4,
Tot_env_100g_scaled_upper_ci = (scaled_upper_ci_GHG + scaled_upper_ci_Eut + scaled_upper_ci_Land + scaled_upper_ci_WatScar)/4,
Tot_env_100g_scaled_min = (scaled_min_GHG + scaled_min_Eut + scaled_min_Land + scaled_min_WatScar)/4,
Tot_env_100g_scaled_max = (scaled_max_GHG + scaled_max_Eut + scaled_max_Land + scaled_max_WatScar)/4,
Tot_env_100g_scaled_lower_fifth = (scaled_lower_fifth_GHG + scaled_lower_fifth_Eut + scaled_lower_fifth_Land + scaled_lower_fifth_WatScar)/4,
Tot_env_100g_scaled_upper_ninetyfifth = (scaled_upper_ninetyfifth_GHG + scaled_upper_ninetyfifth_Eut + scaled_upper_ninetyfifth_Land + scaled_upper_ninetyfifth_WatScar)/4,
Tot_env_100g_scaled = (scaled_mean_GHG + scaled_mean_Eut + scaled_mean_Land + scaled_mean_WatScar)/4) %>%
mutate(Tot_env_100g_scaled_lower_ci = Tot_env_100g_scaled_lower_ci / max(Tot_env_100g_scaled, na.rm = TRUE) * 100,
Tot_env_100g_scaled_upper_ci = Tot_env_100g_scaled_upper_ci / max(Tot_env_100g_scaled, na.rm = TRUE) * 100,
Tot_env_100g_scaled_min = Tot_env_100g_scaled_min / max(Tot_env_100g_scaled, na.rm = TRUE) * 100,
Tot_env_100g_scaled_max = Tot_env_100g_scaled_max / max(Tot_env_100g_scaled, na.rm = TRUE) * 100,
Tot_env_100g_scaled_lower_fifth = Tot_env_100g_scaled_lower_fifth / max(Tot_env_100g_scaled, na.rm = TRUE) * 100,
Tot_env_100g_scaled_upper_ninetyfifth = Tot_env_100g_scaled_upper_ninetyfifth / max(Tot_env_100g_scaled, na.rm = TRUE) * 100,
Tot_env_100g_scaled = Tot_env_100g_scaled / max(Tot_env_100g_scaled, na.rm = TRUE) * 100)
# And returning
return(dat)
}
###
# Extracting serving size and unit
extract.serving.dat <-
function(dat,
serving.col) {
dat <- as.data.frame(dat)
###
# Identifying rows with numbers in the serving data column
rows.nums <- grep("[0-9]",dat[,serving.col])
###
# Extracting numbers from these rows
serving_value_new = str_extract_all(dat[,serving.col], "[0-9]{1,4}(\\s)?(g|kg|l|ml)(\\b|[^A-z])")
serving_value_new2 = str_extract_all(dat[,serving.col], "[0-9]{1,4}(\\s)?\\.(\\s)?[0-9]{1,4}(\\s)?(g|kg|l|ml)(\\b|[^A-z])")
serving_value_new3 = str_extract_all(dat[,serving.col],"1(\\s)?/(\\s)?[0-9]{1,2}")
# Getting priorities
# Value 2 over value 1
# Value 2 and 1 over value 3
# so long as numeric value in 2 and/or 1 does not == 1
# Products with multiple numeric values identified
multiple.list = c()
for(i in 1:length(serving_value_new)) {
# serving value 2 takes precedence over serving value 1
if(serving_value_new2[i] != 'character(0)' & !is.na(serving_value_new2[i])) {
serving_value_new[[i]] <- serving_value_new2[[i]]
}
tmp.value = gsub("[^0-9]","",serving_value_new[[i]])
if(!is.numeric(tmp.value)) {
tmp.value = 1
}
# Serving value 3 takes precedence over value 2 and 1 if value 2and/or1 != 1
if(serving_value_new3[i] != 'character(0)' & !is.na(serving_value_new3[i]) & tmp.value == 1) {
serving_value_new[[i]] <- serving_value_new3[[i]]
}
# Finding which have multiple values reported
if(length(serving_value_new[[i]]) > 1) {
multiple.list <- c(multiple.list,i)
}
}
multiple.list2 = c()
for(i in multiple.list) {
tmp.value = NA
# Series of logical statements
if(is.na(tmp.value)) {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,}(\\s)?g(\\b|[^A-z])")
}
if(is.na(tmp.value) | tmp.value == 'character(0)') {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,4}(\\s)?\\.(\\s)?[0-9]{1,4}(\\s)?g(\\b|[^A-z])")
}
if(is.na(tmp.value) | tmp.value == 'character(0)') {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,}(\\s)?ml(\\b|[^A-z])")
}
if(is.na(tmp.value) | tmp.value == 'character(0)') {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,4}(\\s)?\\.(\\s)?[0-9]{1,4}(\\s)?ml(\\b|[^A-z])")
}
# Series to check if length still > 1
# This catches pastas
if(length(tmp.value[[1]]) > 1) {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,}g(\\s)dry") %>% gsub("(\\s)dry","",.)
}
# This catches pre-mixed noodle dishes
if(length(tmp.value[[1]]) > 1 | tmp.value == 'character(0)' | tmp.value == '0g') {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,}(\\.)?([0-9]{1,})?g(\\s)(no|st|to)") %>%
str_extract_all(.,"[0-9]{1,}(\\.)?([0-9]{1,})?g") %>%
unlist(.) %>% gsub("g","",.) %>% as.numeric(.) %>% sum(.) %>% paste0(.,'g')
}
# This catches filled cookies. Specific, I know.
if(length(tmp.value[[1]]) > 1 | tmp.value == 'character(0)' | tmp.value == '0g') {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,}(\\s)?g(\\s)?=(\\s)?1") %>% gsub("(\\s)=.*","",.) %>% gsub("(\\s)","",.)
}
# This catches tea
if(length(tmp.value[[1]]) > 1 | tmp.value == 'character(0)' | tmp.value == '0g') {
tmp.value = str_extract_all(dat[i,serving.col],"[0-9]{1,}(\\s)?ml") %>% unlist(.) %>% .[1]
}
serving_value_new[[i]] <- tmp.value
}
# Creating new colum for serving data
# And updating this column
dat[,'serving_data_new'] = NA
for(i in 1:nrow(dat)) {
if(length(serving_value_new[[i]]) != 1) {
dat[i,'serving_data_new'] <- NA
} else {
dat[i,'serving_data_new'] <- serving_value_new[[i]]
}
}
# Updating values that are e.g. "1/2" or "1/3"
rows.updates <- grep("[0-9]/[0-9]",dat$serving_data_new)
serving_value_new = str_extract_all(dat[,serving.col], "[0-9]{1,4}(\\s)?(g|kg|l|ml)(\\b|[^A-z])")
serving_value_new2 = str_extract_all(dat[,serving.col], "[0-9]{1,4}(\\s)?\\.(\\s)?[0-9]{1,4}(\\s)?(g|kg|l|ml)(\\b|[^A-z])")
for(i in rows.updates) {
# Products with multiple numeric values identified
multiple.list = c()
# for(i in 1:length(serving_value_new)) {
# serving value 2 takes precedence over serving value 1
if(serving_value_new2[i] != 'character(0)' & !is.na(serving_value_new2[i])) {
serving_value_new[[i]] <- serving_value_new2[[i]]
# }
}
if(length(serving_value_new[[i]] <= 1)) {
dat$serving_data_new[i] <- serving_value_new[[i]]
}
}
# Creating new columns for serving value and unit
dat[,'serving_value_new'] = NA
dat[,'serving_unit_new'] = NA
# And updating these columns
dat[,'serving_value_new'] = gsub("[A-z].*","",dat[,'serving_data_new'], perl = TRUE)
dat[,'serving_unit_new'] = gsub("[0-9]","",dat[,'serving_data_new'], perl = TRUE)
dat[,'serving_unit_new'] = gsub("\\.","",dat[,'serving_unit_new'], perl = TRUE)
# Extracting pack size for products where serving unit == [0-9]/[0-9]
dat[,'pack_size_new'] = NA
dat[,'pack_size_new_2'] = NA
dat[,'pack_size_new'] = str_extract(dat$product_name,"[0-9]{1,}(\\s)?(g|ml|mL|Ml|ML|G|ML|kg|kG|Kg|KG)")
dat[,'pack_size_new_2'] = str_extract(dat$product_name,"[0-9]{1,}.[0-9]{1,}(\\s)?(g|ml|mL|Ml|ML|G|ML|kg|kG|Kg|KG)")
# Updating for periods
dat$pack_size_new[grepl("\\.",dat$pack_size_new_2)] <-
dat$pack_size_new_2[grepl("\\.",dat$pack_size_new_2)]
# L or KG
dat[,'pack_unit'] <- NA
dat[,'pack_unit'] <- str_extract(dat$pack_size_new, "g|ml|mL|Ml|ML|G|ML|kg|kG|Kg|KG")
# Removing units from pack size
dat$pack_size_new <- gsub("[A-z]{1,}","",dat$pack_size_new)
# Updating for kg and L
dat$pack_size_new[dat$pack_unit %in% c('L','l','kg','kG','Kg','KG')] <-
as.numeric(dat$pack_size_new[dat$pack_unit %in% c('l','L','kg','kG','Kg','KG')]) * 1000
dat$pack_size_new <- as.numeric(dat$pack_size_new)
# And updating for products with e.g. 9x37g listed as their pack size
dat$pack_size_new[grepl("[0-9]{1,}(x|X)[0-9]{1,}",dat$pack_size_new_2)] <-
as.numeric(gsub(".*(X|x)","",dat$pack_size_new_2[grepl("[0-9]{1,}(x|X)[0-9]{1,}",dat$pack_size_new_2)]) %>% gsub("(ml|mL|Ml|ML|g)","",.)) *
as.numeric(gsub("(X|x).*","",dat$pack_size_new_2[grepl("[0-9]{1,}(x|X)[0-9]{1,}",dat$pack_size_new_2)]))
# And updating pack unit
dat$pack_unit[dat$pack_unit %in% c('l','L')] <- 'ml'
dat$pack_unit[dat$pack_unit %in% c('kg','Kg','kG','KG')] <- 'g'
# To lower case
dat$pack_unit <- tolower(dat$pack_unit)
# And removing white spaces
dat$pack_size_new <- trimws(dat$pack_size_new, which = 'both')
# Now updating serving size for products where serving = e.g. 1/16 of gateau
dat$serving_value_new[grepl("[0-9]/[0-9]{1,}",dat$serving_value_new)] <-
as.numeric(gsub("/.*","",dat$serving_value_new[grepl("[0-9]/[0-9]{1,}",dat$serving_value_new)])) / # Converting e.g. 1/16 to decimal
as.numeric(gsub(".*/","",dat$serving_value_new[grepl("[0-9]/[0-9]{1,}",dat$serving_value_new)])) * # And multiplying by pack size
as.numeric(dat$pack_size_new[grepl("[0-9]/[0-9]{1,}",dat$serving_value_new)])
# Converting serving to numeric values
dat <-
dat %>%
mutate(serving_value_new = as.numeric(serving_value_new),
pack_size_new = as.numeric(pack_size_new))
# Serving size cannot be greater than pack size
dat$serving_value_new[dat$serving_value_new > dat$pack_size_new & !is.na(dat$serving_value_new) & !is.na(dat$pack_size_new)] <-
NA
# Updating column names
dat <-
dat %>%
dplyr::select(-serving_data) %>% dplyr::select(-serving_value) %>% dplyr::select(-serving_unit) %>%
dplyr::select(-pack_size_new_2) %>% dplyr::select(-pack_unit) %>%
dplyr::rename(serving_data = serving_data_new, serving_value = serving_value_new, serving_unit = serving_unit_new) %>%
mutate(serving_unit = ifelse(serving_value >= 1000, NA, serving_unit),
serving_value = ifelse(serving_value >= 1000, NA, serving_value))
# And returning the data
return(dat)
}
# Function to estimate impacts per serving, calorie, and protein
env.estimate.nutrition.function =
function(dat = dat,
nutrients,
thresholds) {
# Estimating impacts
dat <-
dat %>%
mutate(GHGs_serving = GHGs_100g * (as.numeric(serving_value_updated) / 100),
Eut_serving = Eut_100g * (as.numeric(serving_value_updated) / 100),
WatScar_serving = WatScar_100g * (as.numeric(serving_value_updated) / 100),
Bio_serving = Bio_100g * (as.numeric(serving_value_updated) / 100),
GHGs_10gProtein = GHGs_100g / (Protein / 10),
Eut_10gProtein = Eut_100g / (Protein / 10),
WatScar_10gProtein = WatScar_100g / (Protein / 10),
Bio_10gProtein = Bio_100g / (Protein / 10),
GHGs_100Calories = GHGs_100g / (Calories / 100),
Eut_100Calories = Eut_100g / (Calories / 100),
WatScar_100Calories = WatScar_100g / (Calories / 100),
Bio_100Calories = Bio_100g / (Calories / 100))
# Getting rid of estimates for products with below nutrition threshold
# for(nutrient in nutrients) {
# index.drop = which(dat[,nutrient] < thresholds[which(nutrients %in% nutrient)])
# dat[index.drop,grep(paste0("[0-9](g)?",nutrient), names(dat))] <- NA
# }
# Returning data
return(dat)
}
# Scaling env impacts
env.scaling.function <-
function(dat) {
dat <-
dat %>%
mutate(GHGs_100g_scaled = GHGs_100g / max(.$GHGs_100g, na.rm = TRUE),
Eut_100g_scaled = Eut_100g / max(.$Eut_100g, na.rm = TRUE),
WatScar_100g_scaled = WatScar_100g / max(.$WatScar_100g, na.rm = TRUE),
Bio_100g_scaled = Bio_100g / max(.$Bio_100g, na.rm = TRUE),
GHGs_serving_scaled = GHGs_serving / max(.$GHGs_serving, na.rm = TRUE),
Eut_serving_scaled = Eut_serving / max(.$Eut_serving, na.rm = TRUE),
WatScar_serving_scaled = WatScar_serving / max(.$WatScar_serving, na.rm = TRUE),
Bio_serving_scaled = Bio_serving / max(.$Bio_serving, na.rm = TRUE),
GHGs_protein_scaled = GHGs_10gProtein / max(.$GHGs_10gProtein, na.rm = TRUE),
Eut_protein_scaled = Eut_10gProtein / max(.$Eut_10gProtein, na.rm = TRUE),
WatScar_protein_scaled = WatScar_10gProtein / max(.$WatScar_10gProtein, na.rm = TRUE),
Bio_protein_scaled = Bio_10gProtein / max(.$Bio_10gProtein, na.rm = TRUE),
GHGs_calories_scaled = GHGs_100Calories / max(.$GHGs_100Calories, na.rm = TRUE),
Eut_calories_scaled = Eut_100Calories / max(.$Eut_100Calories, na.rm = TRUE),
WatScar_calories_scaled = WatScar_100Calories / max(.$WatScar_100Calories, na.rm = TRUE),
Bio_calories_scaled = Bio_100Calories / max(.$Bio_100Calories, na.rm = TRUE)) %>%
mutate(TotEnv_100g_scaled = (GHGs_100g_scaled + Eut_100g_scaled + WatScar_100g_scaled + Bio_100g_scaled) / 4,
TotEnv_serving_scaled = (GHGs_serving_scaled + Eut_serving_scaled + WatScar_serving_scaled + Bio_serving_scaled) / 4,
TotEnv_protein_scaled = (GHGs_protein_scaled + Eut_protein_scaled + WatScar_protein_scaled + Bio_protein_scaled) / 4,
TotEnv_calories_scaled = (GHGs_calories_scaled + Eut_calories_scaled + WatScar_calories_scaled + Bio_calories_scaled) / 4)
return(dat)
}
# Scaling env impacts
env.scaling.function.validate <-
function(dat) {
dat <-
dat %>%
mutate(GHGs_100g_scaled = GHGs_100g / max(.$GHGs_100g[.$Validate %in% 'No'], na.rm = TRUE),
Eut_100g_scaled = Eut_100g / max(.$Eut_100g[.$Validate %in% 'No'], na.rm = TRUE),
WatScar_100g_scaled = WatScar_100g / max(.$WatScar_100g[.$Validate %in% 'No'], na.rm = TRUE),
Bio_100g_scaled = Bio_100g / max(.$Bio_100g[.$Validate %in% 'No'], na.rm = TRUE)) %>%
mutate(TotEnv_100g_scaled = (GHGs_100g_scaled + Eut_100g_scaled + WatScar_100g_scaled + Bio_100g_scaled) / 4)
return(dat)
}
###
# Function to update serving sizes
update.serving.size =
function(dat) {
# Summary by shelf
shelf.sum <-
dat %>%
group_by(Retailer, Department, Aisle, Shelf) %>%
summarise(serving_shelf = mean(serving_value, na.rm = TRUE))
# Summary by aisle
aisle.sum <-
dat %>%
group_by(Retailer, Department, Aisle) %>%
summarise(serving_aisle = mean(serving_value, na.rm = TRUE))
# Summary by department
department.sum <-
dat %>%
group_by(Retailer, Department) %>%
summarise(serving_department = mean(serving_value, na.rm = TRUE))
# Merging and updating
dat <-
left_join(dat,
shelf.sum) %>%
left_join(., aisle.sum) %>%
left_join(., department.sum) %>%
mutate(serving_value_updated = ifelse(!is.na(serving_value), serving_value,
ifelse(!is.na(serving_shelf), serving_shelf,
ifelse(!is.na(serving_aisle), serving_aisle,
ifelse(!is.na(serving_department), serving_department, NA))))) %>%
group_by(product_name) %>%
summarise(serving_value_updated = mean(serving_value_updated, na.rm = TRUE))
}
###
# RR function
estimate.rr <-
function(dat, # used only for identifying SSBs
stacked.dat.rr) {
# Importing relative risk data
rr.dat <-
read.csv("/Volumes/Citadel/Oxford/Research Projects/Env and Health Snapshot of FoodDB/Data Inputs/RR_Data_16September2020.csv",
stringsAsFactors = FALSE) %>%
rbind(data.frame(GroupingGroup = 'Potatoes',
DiseaseOutcomeGrouped = 'ACM',
Mean.RR = .88,
Upper.95..RR = 1.12,
Lower.95..RR = .69))
# Adding serving sizes
serving.dat <-
data.frame(Food_Group = c('Chicken','Dairy','Eggs','Fish','Fruits','Legumes','Nuts',
'Olive oil','Potatoes','Processed red meat','Unprocessed red meat',
'Refined grains','SSBs','Vegetables','Whole grains'),
Serving_size = c(100,200,50,100,100,50,28,10,150,50,100,30,225,100,30))
# Adjusting everything to 100g
rr.dat <-
left_join(rr.dat %>% dplyr::rename(Food_Group = GroupingGroup), serving.dat) %>%
mutate(Mean.RR = Mean.RR ^ (100 / Serving_size),
Lower.95..RR = Lower.95..RR ^ (100 / Serving_size),
Upper.95..RR = Upper.95..RR ^ (100 / Serving_size)) %>%
unique(.) %>%
dplyr::select(-Serving_size)
# Sorting into rr_groups
stacked.dat.rr <-
stacked.dat.rr %>%
mutate(rr_group = NA)
# Getting list of negative products
neg.prods <-
unique(stacked.dat.rr$product_name[stacked.dat.rr$percent < 0])
# SSBs
# Allocate SSBs on aisle/shelf
# Identifying SSBs
# To update later
ssb.list <-
unique(c(dat$product_name[dat$drinks %in% 'Drinks' & dat$Sugar_pack_value >= 8],
dat$product_name[dat$drinks %in% 'Drinks' & dat$Sugar >= 8]))
alcohol.list <-
unique(dat$product_name[dat$alcohol %in% 'Alcohol'])
# dat$product_name[grepl('\\bPepsi\\b|\\bCoke\\b|\\bCoca\\b|\\bCola\\b|\\bTropicana\\b|\\bSprite\\b|\\bFanta\\b|\\bGatorade\\b|\\bDr Pepper\\b|\\bMountain Dew\\b|
# \\bRed Bull\\b|\\bPoweraid\\b|\\bPower-Aid\\b|\\bSweetened Iced Tea\\b|\\bJuice\\b|\\bSmoothie\\b', dat$product_name, ignore.case = TRUE) &
# dat$Sugar_pack_value >= 8],
# dat$product_name[grepl('\\bPepsi\\b|\\bCoke\\b|\\bCoca\\b|\\bCola\\b|\\bTropicana\\b|\\bSprite\\b|\\bFanta\\b|\\bGatorade\\b|\\bDr Pepper\\b|\\bMountain Dew\\b|
# \\bRed Bull\\b|\\bPoweraid\\b|\\bPower-Aid\\b|\\bSweetened Iced Tea\\b|\\bJuice\\b|\\bSmoothie\\b', dat$product_name, ignore.case = TRUE) &
# dat$Sugar >= 8]))
# Processed meats
# processed red meat
stacked.dat.rr <-
stacked.dat.rr %>%
mutate(rr_group = ifelse(grepl('bacon|ham|hot(\\s)?dog|beef(\\s)?jerky|biltong|pepperoni|sausage|bratwurst|ham|roast(\\s)?beef|pastrami|corned(\\s)?beef|salami|deli(\\s)?meat|pate(s)?|paté(s)?|pâté(s)?', value, ignore.case = TRUE) & Food_Category %in% c('Pig Meat','Lamb & Mutton','Bovine Meat (beef herd)','Bovine Meat (dairy herd)'), 'Processed red meat', rr_group)) %>%
mutate(rr_group = ifelse(grepl('bacon|ham|hot(\\s)?dog|beef(\\s)?jerky|biltong|pepperoni|sausage|bratwurst|ham|roast(\\s)?beef|pastrami|corned(\\s)?beef|salami|deli(\\s)?meat|pate(s)?|paté(s)?|pâté(s)?|smoked|cured|salted', product_name, ignore.case = TRUE) & Food_Category %in% c('Pig Meat','Lamb & Mutton','Bovine Meat (beef herd)','Bovine Meat (dairy herd)') & is.na(rr_group), 'Processed red meat', rr_group))
# processed meat
stacked.dat.rr <-
stacked.dat.rr %>%
mutate(rr_group = ifelse(grepl('bacon|hot(\\s)?dog|sausage|bratwurst|jerky|pate(s)?|paté(s)?|pâté(s)?', value, ignore.case = TRUE) & Food_Category %in% c('Poultry','Fish (farmed)','Crustaceans (farmed)') & is.na(rr_group), 'Processed white meat', rr_group)) %>%
mutate(rr_group = ifelse(grepl('bacon|hot(\\s)?dog|sausage|bratwurst|jerky|pate(s)?|paté(s)?|pâté(s)?|smoked|cured|salted', product_name, ignore.case = TRUE) & Food_Category %in% c('Poultry','Fish (farmed)','Crustaceans (farmed)') & is.na(rr_group), 'Processed white meat', rr_group))
# Whole grains
stacked.dat.rr <-
stacked.dat.rr %>%
mutate(rr_group = ifelse(grepl('whole(\\s)?grain|whole(\\s)?meal|brown(\\s)?rice|whole|stoneground(\\s)?whole|oats|oatmeal|porridge', value, ignore.case = TRUE) & Food_Category %in% c('Barley (Beer)','Cereals & Oilcrops Misc.','Maize (Meal)','Pasta','Rice','Wheat & Rye (Bread)') & is.na(rr_group), 'Whole grains', rr_group)) %>%
mutate(rr_group = ifelse(grepl('whole(\\s)?grain|whole(\\s)?meal|brown(\\s)?rice|whole|stoneground(\\s)?whole|oats|oatmeal|porridge', product_name, ignore.case = TRUE) & Food_Category %in% c('Barley (Beer)','Cereals & Oilcrops Misc.','Maize (Meal)','Pasta','Rice','Wheat & Rye (Bread)') & is.na(rr_group), 'Whole grains', rr_group))
# Allocate remaining groups
dat.remaining <-
stacked.dat.rr %>%
filter(is.na(rr_group)) %>%
mutate(rr_group = ifelse(Food_Category %in% 'Poultry Meat', 'Chicken',
ifelse(Food_Category %in% c('Milk','Cheese','Butter, Cream & Ghee'), 'Dairy',
ifelse(Food_Category %in% 'Eggs','Eggs',
ifelse(Food_Category %in% c('Fish (farmed)','Crustaceans (farmed)'),'Fish',
ifelse(Food_Category %in% c('Apples','Bananas','Berries & Grapes','Citrus Fruit','Other Fruit'),'Fruits',
ifelse(Food_Category %in% c('Brassicas','Onions & Leeks','Root Vegetables','Tomatoes'),'Vegetables',
ifelse(Food_Category %in% c('Peas','Other Pulses','Tofu'),'Pulses',
ifelse(Food_Category %in% c('Nuts','Sunflower seeds','Groundnuts'),'Nuts',
ifelse(Food_Category %in% c('Olive Oil','Rapeseed Oil','Sunflower Oil'),'Olive Oil',
ifelse(Food_Category %in% c('Potatoes','Cassava'),'Potatoes',
ifelse(Food_Category %in% c('Bovine Meat (beef herd)','Bovine Meat (dairy herd)','Lamb & Mutton','Pig Meat'), 'Unprocessed Red Meat',
ifelse(Food_Category %in% c('Barley (Beer)','Cereals & Oilcrops Misc.','Maize (Meal)','Pasta','Rice','Wheat & Rye (Bread)'), 'Refined grains', rr_group)))))))))))))
# rbinding
dat.out <-
rbind(stacked.dat.rr %>% filter(!is.na(rr_group)),
dat.remaining) %>%
unique(.)
# Removing products with negative percentages
dat.out <-
dat.out %>%
filter(!(product_name %in% neg.prods)) %>%
filter(!(product_name %in% alcohol.list))
# Taking summary by product and rr_group
dat.out <-
dat.out %>%
mutate(value = tolower(value)) %>%
group_by(product_name, rr_group, value) %>%
summarise(percent = mean(percent, na.rm = TRUE)) %>%
as.data.frame(.) %>%
group_by(product_name, rr_group) %>%
summarise(percent = sum(percent, na.rm = TRUE))
# Updating SSBs
dat.out <-
dat.out %>%
mutate(rr_group = ifelse(product_name %in% ssb.list, 'SSBs', rr_group))
# Updating names
dat.out$rr_group[dat.out$rr_group %in% 'Unprocessed Red Meat'] <- "Unprocessed red meat"
dat.out$rr_group[dat.out$rr_group %in% 'Processed white meat'] <- "Processed red meat"
dat.out$rr_group[dat.out$rr_group %in% 'Pulses'] <- "Legumes"
dat.out$rr_group[dat.out$rr_group %in% 'Olive Oil'] <- "Olive oil"
# Merging in health dat
dat.out.rr <-
left_join(dat.out,
rr.dat %>% dplyr::rename (rr_group = Food_Group))
# Updating NAs to 1
dat.out.rr <-
dat.out.rr %>%
filter(!is.na(rr_group)) %>%
mutate(Mean.RR = ifelse(is.na(Mean.RR), 1, Mean.RR)) %>%
mutate(Lower.95..RR = ifelse(is.na(Lower.95..RR), 1, Lower.95..RR)) %>%
mutate(Upper.95..RR = ifelse(is.na(Upper.95..RR), 1, Upper.95..RR))
# Calculating based on percent composition
dat.out.rr <-
dat.out.rr %>%
mutate(percent = ifelse(percent > 100, 100, percent)) %>%
mutate(Mean_RR = Mean.RR ^ (percent / 100),
Lower_RR = Lower.95..RR ^ (percent / 100),
Upper_RR = Upper.95..RR ^ (percent / 100))
# Log transforming so that these can be summed
dat.out.rr <-
dat.out.rr %>%
mutate(Mean_RR = log(Mean_RR),
Lower_RR = log(Lower_RR),
Upper_RR = log(Upper_RR))
# Summing by product
dat.out.rr <-
dat.out.rr %>%
group_by(product_name,DiseaseOutcomeGrouped) %>%
summarise(Mean_RR = sum(Mean_RR, na.rm = TRUE),
Lower_RR = sum(Lower_RR, na.rm = TRUE),
Upper_RR = sum(Upper_RR, na.rm = TRUE))
# And re transforming
dat.out.rr <-
dat.out.rr %>%
mutate(Mean_RR = exp(Mean_RR),
Lower_RR = exp(Lower_RR),
Upper_RR = exp(Upper_RR))
# Returning data frame
return(dat.out.rr)
}
###
# Search terms to sort ingredients into the relative risk groups
search.rr.function <-
function(dat) {
# Creating new column
dat <-
dat %>%
mutate(rr_group = NA)
# Need search terms for red meat
# processed red meat
dat <-
dat %>%
mutate(rr_group = ifelse(grepl('bacon|ham|hot(\\s)?dog|beef(\\s)?jerky|biltong|pepperoni|sausage|bratwurst|ham|roast(\\s)?beef|pastrami|corned(\\s)?beef|salami|deli(\\s)?meat|pate(s)?|paté(s)?|pâté(s)?|smoked|cured|salted', value, ignore.case = TRUE) & Food_Category %in% c('Pigmeat','Lamb & Mutton','Bovine Meat (beef herd)','Bovine Meat (dairy herd)'), 'Processed red meat')) %>%
mutate(rr_group = ifelse(grepl('bacon|ham|hot(\\s)?dog|beef(\\s)?jerky|biltong|pepperoni|sausage|bratwurst|ham|roast(\\s)?beef|pastrami|corned(\\s)?beef|salami|deli(\\s)?meat|pate(s)?|paté(s)?|pâté(s)?|smoked|cured|salted', product_name, ignore.case = TRUE) & Food_Category %in% c('Pigmeat','Lamb & Mutton','Bovine Meat (beef herd)','Bovine Meat (dairy herd)') & is.na(rr_group), 'Processed red meat'))
# processed meat
dat <-
dat %>%
mutate(rr_group = ifelse(grepl('bacon|hot(\\s)?dog|sausage|bratwurst|jerky|pate(s)?|paté(s)?|pâté(s)?|smoked|cured|salted', value, ignore.case = TRUE) & Food_Category %in% c('Poultry','Fish (farmed)','Crustaceans (farmed)') & is.na(rr_group), 'Processed white meat')) %>%
mutate(rr_group = ifelse(grepl('bacon|hot(\\s)?dog|sausage|bratwurst|jerky|pate(s)?|paté(s)?|pâté(s)?|smoked|cured|salted', product_name, ignore.case = TRUE) & Food_Category %in% c('Poultry','Fish (farmed)','Crustaceans (farmed)') & is.na(rr_group), 'Processed white meat'))
# Whole grains
dat <-
dat %>%
mutate(rr_group = ifelse(grepl('whole(\\s)?grain|whole(\\s)?meal|brown(\\s)?rice|whole|stoneground(\\s)?whole|oats|oatmeal|porridge', value, ignore.case = TRUE) & Food_Category %in% c('Barley (Beer)','Cereals & Oilcrops Misc.','Maize (Meal)','Pasta','Rice','Wheat & Rye (Bread)') & is.na(rr_group), 'Whole grains')) %>%
mutate(rr_group = ifelse(grepl('whole(\\s)?grain|whole(\\s)?meal|brown(\\s)?rice|whole|stoneground(\\s)?whole|oats|oatmeal|porridge', product_name, ignore.case = TRUE) & Food_Category %in% c('Barley (Beer)','Cereals & Oilcrops Misc.','Maize (Meal)','Pasta','Rice','Wheat & Rye (Bread)') & is.na(rr_group), 'Whole grains')) %>%
# dat <-
# dat %>%
# mutate(rr_group = ifelse(Aisle %in% c('Coca Cola Shop','Cordials',''), 'SSBs',NA)) %>%
# mutate(rr_group = ifelse(Shelf %in% c(), 'SSBs',NA))
# Allocate chicken, dairy, eggs, fish, fruits, legumes, nuts
# olive oil (and other oils), potatoes, and vegetables based on LCA categories
dat.remaining <-
dat %>%
filter(is.na(rr_group)) %>%
mutate(rr_group = ifelse(Food_Category %in% 'Poultry', 'Chicken',
ifelse(Food_Category %in% c('Milk','Cheese','Butter, Cream & Ghee'), 'Dairy',
ifelse(Food_Category %in% 'Eggs','Eggs',
ifelse(Food_Category %in% c('Fish (farmed)','Crustaceans (farmed)'),'Fish',
ifelse(Food_Category %in% c('Apples','Bananas','Berries & Grapes','Citrus Fruit','Other Fruit'),'Fruits',
ifelse(Food_Category %in% c('Brassicas','Onions & Leeks','Root Vegetables','Tomatoes'),'Vegetables',
ifelse(Food_Category %in% c('Peas','Other Pulses','Tofu'),'Pulses',
ifelse(Food_Category %in% c('Nuts','Sunflower seeds','Groundnuts'),'Nuts',
ifelse(Food_Category %in% c('Olive Oil','Rapeseed Oil','Sunflower Oil'),'Olive Oil',
ifelse(Food_Category %in% c('Potatoes','Cassava'),'Potatoes',
ifelse(Food_Category %in% c('Bovine Meat (beef herd)','Bovine Meat (dairy herd)','Lamb & Mutton','Pig Meat'), 'Unprocessed Red Meat',
ifelse(Food_Category %in% c('Barley (Beer)','Cereals & Oilcrops Misc.','Maize (Meal)','Pasta','Rice','Wheat & Rye (Bread)'), 'Refined grains')))))))))))))
}
# monte carlo function for lca estimates
# WIth organic and fish incorporated
monte.carlo.lca <-
function(product.list) {
# setting for reproducability
set.seed(19)
# updating to work with code below
lca <-