-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path.Rhistory
512 lines (512 loc) · 20.1 KB
/
.Rhistory
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
library("ggResidpanel")
library(dplyr)
library(emmeans)
getwd()
file_path <- "processed/input/model/"
# Specify the crops
crops <- c("Corn", "Rice", "Soybean", "Wheat")
#######################################################
###Load and prepare model input data###################
######################################################
print("Reading crop and index data and defining calibration data")
# Load the clean data set for each crop and extract the model calibration
# data set by dropping all rows of the validation data set
model_data <- list()
val_index <- list()
fit_data <- list()
for (crop in crops) {
model_data[[crop]] <- read.csv(paste0(file_path, crop, "_data.gzip"),
header=TRUE, sep=",", row.names=1, quote="",
comment="", stringsAsFactors=FALSE)
val_index[[crop]] <- read.csv(paste0(file_path, crop, "_index.csv"),
header=TRUE, sep=",", quote="",
comment="", stringsAsFactors=FALSE)
model_data[[crop]][, sapply(model_data[[crop]], is.integer)] <- lapply(model_data[[crop]][,
sapply(model_data[[crop]], is.integer)], as.factor)
#subtract the rows of the val_index data (which represent 20% of the model data,
#to be used for model validation) from the clean data set to be left with 80%
#of the model data to fit the model
fit_data[[crop]] <- model_data[[crop]][!rownames(model_data[[crop]]) %in% val_index[[crop]][["X0"]],]
}
print("Fitting the GLM and calculating the VIF")
model <- list()
VIF <- list()
inf_fact <- list()
for (crop in crops) {
# Fit gamma GLM with log link
#specify the model for each crop with a gamma distribution and the independent factors total nitrogen application,
#artificial phosphorus fertilizer application, total irrigation, pesticide application, temperature +
#moisture + soil class and a dummy indicating if the area is worked with agricultural machinery
model[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data[[crop]],
family = Gamma(link = "log")
)
#Calculate VIF
#calculate GVIF, Df and GVIF^1/2*Df and save it in a data frame
inf_fact[[crop]] <- vif(model[[crop]])
VIF[[crop]] <- data.frame(inf_fact[crop])
}
summary(model[[crop]])
stand_data <- list()
sd_stand <- list()
mean_stand <- list()
stand_pred <- list()
fit_data_sd <- list()
norm1 <- list()
norm2 <- list()
norm_pred <- list()
fit_data_norm <- list()
for (crop in crops) {
stand_data[[crop]] <- fit_data[[crop]][, c(6, 8, 9, 10)]
sd_stand[[crop]] <- apply(stand_data[[crop]], 2, sd)
mean_stand[[crop]] <- apply(stand_data[[crop]], 2, mean)
stand_pred[[crop]] <- (stand_data[[crop]] - mean_stand[[crop]])/ sd_stand[[crop]]
fit_data_sd[[crop]] <- cbind(stand_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
norm1[[crop]] <- stand_data[[crop]] - apply(stand_data[[crop]], 2, min)
norm2[[crop]] <- apply(stand_data[[crop]], 2, function(x) max(x) - min(x))
norm_pred[[crop]] <- sweep(norm1[[crop]], 2, norm2[[crop]], `/`)
fit_data_norm[[crop]] <- cbind(norm_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
}
model_stand <- list()
model_norm <- list()
for (crop in crops) {
model_stand[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_sd[[crop]],
family = Gamma(link = "log")
)
model_norm[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_norm[[crop]],
family = Gamma(link = "log")
)
}
stand_data <- list()
sd_stand <- list()
mean_stand <- list()
stand_pred <- list()
fit_data_sd <- list()
norm1 <- list()
norm2 <- list()
norm_pred <- list()
fit_data_norm <- list()
for (crop in crops) {
stand_data[[crop]] <- fit_data[[crop]][, c(6, 8, 9, 10)]
sd_stand[[crop]] <- apply(stand_data[[crop]], 2, sd)
mean_stand[[crop]] <- apply(stand_data[[crop]], 2, mean)
stand_pred[[crop]] <- (stand_data[[crop]] - mean_stand[[crop]])/ sd_stand[[crop]]
fit_data_sd[[crop]] <- cbind(stand_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
norm1[[crop]] <- stand_data[[crop]] - apply(stand_data[[crop]], 2, min)
norm2[[crop]] <- apply(stand_data[[crop]], 2, function(x) max(x) - min(x))
norm_pred[[crop]] <- sweep(norm1[[crop]], 2, norm2[[crop]], `/`)
fit_data_norm[[crop]] <- cbind(norm_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
}
View(fit_data)
model_stand <- list()
model_norm <- list()
for (crop in crops) {
model_stand[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_sd[[crop]],
family = Gamma(link = "log")
)
model_norm[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_norm[[crop]],
family = Gamma(link = "log")
)
}
library(car)
library(openxlsx)
library(ggplot2)
library("ggResidpanel")
library(dplyr)
library(emmeans)
# Define input file path
getwd()
file_path <- "processed/input/model/"
# Specify the crops
crops <- c("Corn", "Rice", "Soybean", "Wheat")
print("Reading crop and index data and defining calibration data")
# Load the clean data set for each crop and extract the model calibration
# data set by dropping all rows of the validation data set
model_data <- list()
val_index <- list()
fit_data <- list()
for (crop in crops) {
model_data[[crop]] <- read.csv(paste0(file_path, crop, "_data.gzip"),
header=TRUE, sep=",", row.names=1, quote="",
comment="", stringsAsFactors=FALSE)
val_index[[crop]] <- read.csv(paste0(file_path, crop, "_index.csv"),
header=TRUE, sep=",", quote="",
comment="", stringsAsFactors=FALSE)
model_data[[crop]][, sapply(model_data[[crop]], is.integer)] <- lapply(model_data[[crop]][,
sapply(model_data[[crop]], is.integer)], as.factor)
#subtract the rows of the val_index data (which represent 20% of the model data,
#to be used for model validation) from the clean data set to be left with 80%
#of the model data to fit the model
fit_data[[crop]] <- model_data[[crop]][!rownames(model_data[[crop]]) %in% val_index[[crop]][["X0"]],]
}
stand_data <- list()
sd_stand <- list()
mean_stand <- list()
stand_pred <- list()
fit_data_sd <- list()
norm1 <- list()
norm2 <- list()
norm_pred <- list()
fit_data_norm <- list()
for (crop in crops) {
stand_data[[crop]] <- fit_data[[crop]][, c(6, 8, 9, 10)]
sd_stand[[crop]] <- apply(stand_data[[crop]], 2, sd)
mean_stand[[crop]] <- apply(stand_data[[crop]], 2, mean)
stand_pred[[crop]] <- (stand_data[[crop]] - mean_stand[[crop]])/ sd_stand[[crop]]
fit_data_sd[[crop]] <- cbind(stand_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
norm1[[crop]] <- stand_data[[crop]] - apply(stand_data[[crop]], 2, min)
norm2[[crop]] <- apply(stand_data[[crop]], 2, function(x) max(x) - min(x))
norm_pred[[crop]] <- sweep(norm1[[crop]], 2, norm2[[crop]], `/`)
fit_data_norm[[crop]] <- cbind(norm_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
}
model_stand <- list()
model_norm <- list()
for (crop in crops) {
model_stand[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_sd[[crop]],
family = Gamma(link = "log")
)
model_norm[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_norm[[crop]],
family = Gamma(link = "log")
)
}
stand_data <- list()
sd_stand <- list()
mean_stand <- list()
stand_pred <- list()
fit_data_sd <- list()
norm1 <- list()
norm2 <- list()
norm_pred <- list()
fit_data_norm <- list()
for (crop in crops) {
stand_data[[crop]] <- fit_data[[crop]][, c(6, 8, 9, 10)]
sd_stand[[crop]] <- apply(stand_data[[crop]], 2, sd)
mean_stand[[crop]] <- apply(stand_data[[crop]], 2, mean)
stand_pred[[crop]] <- (stand_data[[crop]] - mean_stand[[crop]])/ sd_stand[[crop]]
fit_data_sd[[crop]] <- cbind(stand_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
norm1[[crop]] <- stand_data[[crop]] - apply(stand_data[[crop]], 2, min)
norm2[[crop]] <- apply(stand_data[[crop]], 2, function(x) max(x) - min(x))
norm_pred[[crop]] <- sweep(norm1[[crop]], 2, norm2[[crop]], `/`)
fit_data_norm[[crop]] <- cbind(norm_pred[[crop]], fit_data[[crop]][, c(4, 12, 13, 14, 15)])
}
model_stand <- list()
model_norm <- list()
View(fit_data)
View(fit_data)
View(stand_data)
for (crop in crops) {
stand_data[[crop]] <- fit_data[[crop]][, c(7, 8, 9)]
sd_stand[[crop]] <- apply(stand_data[[crop]], 2, sd)
mean_stand[[crop]] <- apply(stand_data[[crop]], 2, mean)
stand_pred[[crop]] <- (stand_data[[crop]] - mean_stand[[crop]])/ sd_stand[[crop]]
fit_data_sd[[crop]] <- cbind(stand_pred[[crop]], fit_data[[crop]][, c(4, 11, 12, 13, 14)])
norm1[[crop]] <- stand_data[[crop]] - apply(stand_data[[crop]], 2, min)
norm2[[crop]] <- apply(stand_data[[crop]], 2, function(x) max(x) - min(x))
norm_pred[[crop]] <- sweep(norm1[[crop]], 2, norm2[[crop]], `/`)
fit_data_norm[[crop]] <- cbind(norm_pred[[crop]], fit_data[[crop]][, c(4, 11, 12, 13, 14)])
}
model_stand <- list()
model_norm <- list()
View(stand_data)
for (crop in crops) {
model_stand[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_sd[[crop]],
family = Gamma(link = "log")
)
model_norm[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_norm[[crop]],
family = Gamma(link = "log")
)
}
summary(model_stand[['Corn']])
exp(coef(model_stand[['Corn']]))
exp(coef(model_norm[['Corn']]))
exp(coef(model[['Corn']]))
print("Fitting the GLM and calculating the VIF")
model <- list()
VIF <- list()
inf_fact <- list()
for (crop in crops) {
# Fit gamma GLM with log link
#specify the model for each crop with a gamma distribution and the independent factors total nitrogen application,
#artificial phosphorus fertilizer application, total irrigation, pesticide application, temperature +
#moisture + soil class and a dummy indicating if the area is worked with agricultural machinery
model[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data[[crop]],
family = Gamma(link = "log")
)
#Calculate VIF
#calculate GVIF, Df and GVIF^1/2*Df and save it in a data frame
inf_fact[[crop]] <- vif(model[[crop]])
VIF[[crop]] <- data.frame(inf_fact[crop])
}
exp(coef(model[['Corn']]))
exp(coef(model_norm[['Corn']]))
summary(model_stand[['Corn']])
exp(coef(model_stand[['Corn']]))
exp(coef(model_norm[['Corn']]))
exp(coef(model[['Corn']]))
View(sd_stand)
View(norm1)
View(norm2)
stand_data[['Corn']].max()
apply(stand_data[[crop]], 2, max)
stand_ max <- apply(stand_data[[crop]], 2, max)
stand_max <- apply(stand_data[[crop]], 2, max)
sweep(stand_max[[crop]], 2, sd_stand[[crop]], `/`)
sweep(stand_max, 2, sd_stand[[crop]], `/`)
stand_max <- apply(stand_data[[crop]], 2, max)
view(stand_max)
View(stand_max)
sd_wheat <- sd_stand[[crop]]
sweep(stand_max, 2, sd_wheat, `/`)
sweep(stand_max, sd_wheat, `/`)
stand_max/sd_wheat
exp(coef(model_stand[['Wheat']]))
exp(coef(model_norm[['Wheat']]))
exp(coef(model[['Wheat']]))
1.1114998*4.617118
0.1114998*4.617118
0.0005584*4.479073
0.0015654*379.8
0.3065802*1.836081
predict(model[[crop]], type="link")
View(stand_data)
View(fit_data_norm)
test <- data.frame(n_total = cbind(0, 379.80), pesticides = cbind(1.5, 1.5), irrigation_tot = cbind(0.8, 0.8),
mechanized = cbind(1, 1), thz_class = cbind(2, 2), mst_class = cbind(4, 4), soil_class = cbind(3,3))
View(test)
test <- data.frame(n_total = 0, 379.80, pesticides = 1.5, 1.5, irrigation_tot = 0.8, 0.8,
mechanized = 1, 1, thz_class = 2, 2, mst_class = 4, 4, soil_class = 3,3)
test <- data.frame(n_total = c(0, 379.80), pesticides = c(1.5, 1.5), irrigation_tot = c(0.8, 0.8),
mechanized = c(1, 1), thz_class = c(2, 2), mst_class = c(4, 4), soil_class = c(3,3))
test1 <- data.frame(n_total = c(0, 379.80), pesticides = c(1.5, 1.5), irrigation_tot = c(0.8, 0.8),
mechanized = c(1, 1), thz_class = c(2, 2), mst_class = c(4, 4), soil_class = c(3,3))
View(test1)
predict(model[[crop]], test1,type="response")
test1 <- data.frame(n_total = c(0, 379.80), pesticides = c(1.5, 1.5), irrigation_tot = c(0.8, 0.8),
mechanized = factor(c(1, 1)), thz_class = c(2, 2), mst_class = c(4, 4), soil_class = c(3,3))
View(test1)
test1 <- data.frame(n_total = c(0, 379.80), pesticides = c(1.5, 1.5), irrigation_tot = c(0.8, 0.8),
mechanized = factor(c(1, 1)), thz_class = factor(c(2, 2)), mst_class = factor(c(4, 4)), soil_class = factor(c(3,3)))
predict(model[[crop]], test1,type="response")
4331.759*1.8113423
test1 <- data.frame(n_total = c(150, 150), pesticides = c(0, 1.836081), irrigation_tot = c(0.8, 0.8),
mechanized = factor(c(1, 1)), thz_class = factor(c(2, 2)), mst_class = factor(c(4, 4)), soil_class = factor(c(3,3)))
predict(model[[crop]], test1,type="response")
0.3065802*1.6339349
3667.393* 1.6339349
View(sd_stand)
test1 <- data.frame(n_total = c(150, 150), pesticides = c(0, 0.3976683), irrigation_tot = c(0.8, 0.8),
mechanized = factor(c(1, 1)), thz_class = factor(c(2, 2)), mst_class = factor(c(4, 4)), soil_class = factor(c(3,3)))
predict(model[[crop]], test1,type="response")
3667.393* 1.1114998
test1 <- data.frame(n_total = c(0, 84.79326), pesticides = c(1.5, 1.5), irrigation_tot = c(0.8, 0.8),
mechanized = factor(c(1, 1)), thz_class = factor(c(2, 2)), mst_class = factor(c(4, 4)), soil_class = factor(c(3,3)))
predict(model[[crop]], test1,type="response")
4331.759*1.0005584
coef_wheat <- coef(model[[crop]])
coef_wheat <- coef(model[[crop]], type='response')
View(coef_wheat)
coef_wheat <- coef(model[[crop]])
sd_wheat <- apply(fit_data[[crop]], 2, sd)
View(sd_wheat)
sd_wheat[1]
stand1 <- coef_wheat * sd_wheat[4]
sd_wheat[4]
View(stand1)
View(coef_wheat)
stand1 <- coef_wheat[c(2,3,5)] * sd_wheat[4]
stand2 <- stand1/sd_wheat[7,8,9]
xasadifl <- sd_wheat[7,8,9]
stand2 <- stand1/sd_wheat[c(7,8,9)]
View(stand2)
stand1 <- coef_wheat[c(2,3,5)] * sd_wheat[c(7,8,9)]
stand2 <- stand1/sd_wheat[4]
View(stand2)
test2 <- predict(model[[crop]], test1,type="response")
test2[2]/test2[1]
test2[1]/test2[2]
View(test2)
test1 <- data.frame(n_total = c(0, 379.7951), pesticides = c(1.5, 1.5), irrigation_tot = c(0.8, 0.8),
mechanized = factor(c(1, 1)), thz_class = factor(c(2, 2)), mst_class = factor(c(4, 4)), soil_class = factor(c(3,3)))
test2 <- predict(model[[crop]], test1,type="response")
test2[1]/test2[2]
View(test2)
test1 <- data.frame(n_total = c(0, 379.7951), pesticides = c(1.836081, 1.836081), irrigation_tot = c(1, 1),
mechanized = factor(c(1, 1)), thz_class = factor(c(7, 7)), mst_class = factor(c(5, 5)), soil_class = factor(c(6,6)))
test2 <- predict(model[[crop]], test1,type="response")
test2[1]/test2[2]
norm_data <- lapply(crops, function(crop) fit_data[[crop]][, c(7, 8, 9)])
norm1 <- lapply(norm_data, function(data) data - apply(data, 2, min))
norm2 <- lapply(norm_data, function(data) apply(data, 2, function(x) max(x) - min(x)))
norm_pred <- Map(function(x, y) sweep(x, 2, y, `/`), norm1, norm2)
fit_data_norm <- Map(function(x, crop) cbind(x, fit_data[[crop]][, c(4, 11, 12, 13, 14)]), norm_pred, crops)
View(fit_data_norm)
View(fit_data_norm)
model_norm <- list()
for (crop in crops) {
model_norm[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_norm[[crop]],
family = Gamma(link = "log")
)
}
norm_data <- list()
norm1 <- list()
norm2 <- list()
norm_pred <- list()
fit_data_norm <- list()
for (crop in crops) {
norm_data[[crop]] <- fit_data[[crop]][, c(7, 8, 9)]
norm1[[crop]] <- norm_data[[crop]] - apply(norm_data[[crop]], 2, min)
norm2[[crop]] <- apply(norm_data[[crop]], 2, function(x) max(x) - min(x))
norm_pred[[crop]] <- sweep(norm1[[crop]], 2, norm2[[crop]], `/`)
fit_data_norm[[crop]] <- cbind(norm_pred[[crop]], fit_data[[crop]][, c(4, 11, 12, 13, 14)])
}
model_norm <- list()
for (crop in crops) {
model_norm[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data_norm[[crop]],
family = Gamma(link = "log")
)
}
#combine all four data frames of VIF[[crop]] into one data frame
VIF_crops <- bind_cols(VIF)
for (crop in crops) {
VIF_crops <- VIF_crops %>%
mutate(!!paste0(crop, ".GVIF2") := (!!sym(paste0(crop, ".GVIF..1..2.Df.."))) ^ 2)
}
#order the columns alphabetically
VIF_crops <- VIF_crops[, order(names(VIF_crops))]
hs2 <- createStyle(
fontColour = "#000000", halign = "center",
valign = "center", textDecoration = "bold",
border = "TopBottomLeftRight"
)
# Load the existing Excel file
wb <- loadWorkbook("reports/Model_results.xlsx")
# remove the worksheet if a sheet with that name already exists
#removeWorksheet(wb, sheet = "Model_VIF")
# Add a new sheet with your data frame
addWorksheet(wb, "Model_VIF")
writeDataTable(wb, sheet = "Model_VIF", x = VIF_crops, rowNames=TRUE,
tableStyle = "None", headerStyle = hs2, firstColumn = TRUE)
# Save the updated Excel file
saveWorkbook(wb, "reports/Model_results.xlsx", overwrite = TRUE)
addWorksheet(wb, "Model_VIF")
# Load the existing Excel file
wb <- loadWorkbook("reports/Model_results.xlsx")
addWorksheet(wb, "Model_VIF")
writeDataTable(wb, sheet = "Model_VIF", x = VIF_crops, rowNames=TRUE,
tableStyle = "None", headerStyle = hs2, firstColumn = TRUE)
# Load the existing Excel file
wb <- loadWorkbook("reports/Model_results.xlsx")
addWorksheet(wb, "Model_VIF")
writeDataTable(wb, sheet = "Model_VIF", x = VIF_crops, rowNames=TRUE,
tableStyle = "None", headerStyle = hs2, firstColumn = TRUE)
# Save the updated Excel file
saveWorkbook(wb, "reports/Model_results.xlsx", overwrite = TRUE)
library(car)
library(openxlsx)
library(ggplot2)
library("ggResidpanel")
library(dplyr)
library(emmeans)
# Define input file path
getwd()
file_path <- "processed/input/model/"
# Specify the crops
crops <- c("Corn", "Rice", "Soybean", "Wheat")
model_data <- list()
val_index <- list()
fit_data <- list()
for (crop in crops) {
model_data[[crop]] <- read.csv(paste0(file_path, crop, "_data.gzip"),
header=TRUE, sep=",", row.names=1, quote="",
comment="", stringsAsFactors=FALSE)
val_index[[crop]] <- read.csv(paste0(file_path, crop, "_index.csv"),
header=TRUE, sep=",", quote="",
comment="", stringsAsFactors=FALSE)
model_data[[crop]][, sapply(model_data[[crop]], is.integer)] <- lapply(model_data[[crop]][,
sapply(model_data[[crop]], is.integer)], as.factor)
#subtract the rows of the val_index data (which represent 20% of the model data,
#to be used for model validation) from the clean data set to be left with 80%
#of the model data to fit the model
fit_data[[crop]] <- model_data[[crop]][!rownames(model_data[[crop]]) %in% val_index[[crop]][["X0"]],]
}
model <- list()
VIF <- list()
inf_fact <- list()
for (crop in crops) {
# Fit gamma GLM with log link
#specify the model for each crop with a gamma distribution and the independent factors total nitrogen application,
#artificial phosphorus fertilizer application, total irrigation, pesticide application, temperature +
#moisture + soil class and a dummy indicating if the area is worked with agricultural machinery
model[[crop]] <- glm(
formula = Yield ~ n_total + irrigation_tot + mechanized + pesticides +
thz_class + mst_class + soil_class,
data = fit_data[[crop]],
family = Gamma(link = "log")
)
#Calculate VIF
#calculate GVIF, Df and GVIF^1/2*Df and save it in a data frame
inf_fact[[crop]] <- vif(model[[crop]])
VIF[[crop]] <- data.frame(inf_fact[crop])
}
#combine all four data frames of VIF[[crop]] into one data frame
VIF_crops <- bind_cols(VIF)
#create a new column for each crop that squares the "GVIF^1/2*Df" column
#for variables with Df=1 the squared "GVIF^1/2*Df" values equal the GVIF
#this new column can be interpreted with the same rules of thumb as the VIF
for (crop in crops) {
VIF_crops <- VIF_crops %>%
mutate(!!paste0(crop, ".GVIF2") := (!!sym(paste0(crop, ".GVIF..1..2.Df.."))) ^ 2)
}
#order the columns alphabetically
VIF_crops <- VIF_crops[, order(names(VIF_crops))]
View(VIF_crops)
VIF_crops <- round(VIF_crops, digits=2)
View(VIF_crops)
hs2 <- createStyle(
fontColour = "#000000", halign = "center",
valign = "center", textDecoration = "bold",
border = "TopBottomLeftRight"
)
# Load the existing Excel file
wb <- loadWorkbook("reports/Model_results.xlsx")
addWorksheet(wb, "Model_VIF")
writeDataTable(wb, sheet = "Model_VIF", x = VIF_crops, rowNames=TRUE,
tableStyle = "None", headerStyle = hs2, firstColumn = TRUE)
# Save the updated Excel file
saveWorkbook(wb, "reports/Model_results.xlsx", overwrite = TRUE)
print("Done saving the VIF to the 'reports/Model_Results.xlsx' file")