-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path.Rhistory
512 lines (512 loc) · 15.6 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
# Perform independent test with known covariance matrix
covMat <- cov(X) # Example covariance matrix
independent_test(X, covMat = covMa
independent_test <- function(X, covMat = NULL, alpha = NULL) {
independent_test <- function(X, covMat = NULL, alpha = NULL) {
n <- nrow(X)
p <- ncol(X)
# Maximum likelihood estimator of covariance matrix
A <- (n - 1) * cov(X)
sig <- diag(cov(X))
W <- colSums(X)
if (is.null(covMat)) {
# Sigma unknown
test_statistic <- (n - 1) * var(W) / sum(sig)
df <- n - 1
} else {
# Sigma known
test_statistic <- (n - 1) * var(W) / sum(diag(covMat))
df <- n - 1
}
# Define significance levels (alphas)
alphas <- c(0.01, 0.05, 0.01, 0.05, 0.1, 0.2, 0.5)
# Calculate p-values for both tails
p_values_upper <- pchisq(test_statistic, df = df, lower.tail = FALSE)
p_values_lower <- pchisq(test_statistic, df = df, lower.tail = TRUE)
# Calculate final p-value using the minimum of probabilities
p_value <- 2 * pmin(p_values_upper, p_values_lower)
# Create a data frame to store results
results <- data.frame(Test_Statistic = test_statistic,
Alpha = alphas,
P_Value = p_value,
Test_Result = ifelse(p_value <= alphas, "Reject H0", "Fail to Reject H0"))
if (!is.null(alpha)) {
result <- data.frame(Test_Statistic = test_statistic,
Alpha = alpha,
P_Value = p_value,
Test_Result = ifelse(p_value <= alphas, "Reject H0", "Fail to Reject H0"))
return(result)
}
return(results)
}
# Example usage
set.seed(123) # for reproducibility
X <- matrix(rnorm(100), ncol = 5) # Example data
# Perform independent test without specifying alpha
independent_test(X)
independent_test <- function(X, covMat = NULL, alpha = NULL) {
n <- nrow(X)
p <- ncol(X)
# Maximum likelihood estimator of covariance matrix
A <- (n - 1) * cov(X)
sig <- diag(cov(X))
W <- colSums(X)
if (is.null(covMat)) {
# Sigma unknown
test_statistic <- (n - 1) * var(W) / sum(sig)
df <- n - 1
} else {
# Sigma known
test_statistic <- (n - 1) * var(W) / sum(diag(covMat))
df <- n - 1
}
# Define significance levels (alphas)
alphas <- c(0.01, 0.05, 0.01, 0.05, 0.1, 0.2, 0.5)
# Calculate p-values for both tails
p_values_upper <- pchisq(test_statistic, df = df, lower.tail = FALSE)
p_values_lower <- pchisq(test_statistic, df = df, lower.tail = TRUE)
# Calculate final p-value using the minimum of probabilities
p_value <- 2 * pmin(p_values_upper, p_values_lower)
# Create a data frame to store results
results <- data.frame(Test_Statistic = test_statistic,
Degrees_of_Freedom = df,
Alpha = alphas,
P_Value = p_value,
Test_Result = ifelse(p_value <= alphas, "Reject H0", "Fail to Reject H0"))
if (!is.null(alpha)) {
result <- data.frame(Test_Statistic = test_statistic,
Degrees_of_Freedom = df,
Alpha = alpha,
P_Value = p_value,
Test_Result = ifelse(p_value <= alphas, "Reject H0", "Fail to Reject H0"))
return(result)
}
return(results)
}
# Example usage
set.seed(123) # for reproducibility
X <- matrix(rnorm(100), ncol = 5) # Example data
# Perform independent test without specifying alpha
independent_test(X)
# Perform independent test with alpha = 0.05
independent_test(X, alpha = 0.05)
covMat <- covMatCS(5)
covMat
covMatC <- function(p, sigma2 = 1, rho = NULL) {
if (is.null(rho)) {
rho <- stats::runif(1) # If rho is not provided, generate a random value between 0 and 1
}
# Create an empty matrix
matrix <- matrix(0, nrow = p, ncol = p)
# Populate the covariance matrix
for (i in 1:p) {
for (j in 1:p) {
if (i == j) {
matrix[i, j] <- sigma2
} else {
distance <- min(abs(i - j), p - abs(i - j))
matrix[i, j] <- sigma2 * exp(-rho * distance)
}
}
}
if (matrixcalc::is.positive.definite(matrix)) {
message <- "The covariance matrix is positive definite."
} else {
message <- "The covariance matrix is not positive definite."
}
cat(message, "\n")
return(matrix)
}
covMatC(p = 5)
covMatC <- function(p, sigma2 = 1, rho = NULL) {
if (is.null(rho)) {
rho <- stats::runif(1) # If rho is not provided, generate a random value between 0 and 1
}
# Create an empty matrix
matrix <- matrix(0, nrow = p, ncol = p)
# Populate the covariance matrix
for (i in 1:p) {
for (j in 1:p) {
if (i == j) {
matrix[i, j] <- sigma2
} else {
distance <- min(abs(i - j), p - abs(i - j))
matrix[i, j] <- sigma2 * exp(-rho * distance)
}
}
}
if (matrixcalc::is.positive.definite(matrix)) {
message <- "The covariance matrix is positive definite."
} else {
message <- "The covariance matrix is not positive definite."
}
cat(message, "\n")
cat("\n")
return(matrix)
}
covMatC(5)
mat = covMatC(5)
mat
covMat <- covMatCS(5)
covMat
covMatCS(5)
covMat <- covMatC(5)
covMat
covMat <- covMatC(5)
covMat
X <- mvrnorm(n = 100, mu = rep(0,5), Sigma = covMat)
X <- mvrnorm(n = 100, mu = rep(0,5), Sigma = covMat)
X <- MASS::mvrnorm(n = 100, mu = rep(0,5), Sigma = covMat)
# Perform independent test with alpha = 0.05
independent_test(X, alpha = 0.05)
covMat <- diag(5)
X <- MASS::mvrnorm(n = 100, mu = rep(0,5), Sigma = covMat)
# Perform independent test with alpha = 0.05
independent_test(X, alpha = 0.05)
library(indepTest)
library(indepTest)
library(indepTest)
library(indepTest)
library(indepTest)
cov_mat
library(MASS)
n = 100 # Sample Size
p = 5
rho = 0.014
# Covariance structure with Autoregressive structure
cov_mat <- covMatAR(p = p, rho = rho)
cov_mat
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
indTest(data)
#'
#' #' # Covariance structure with Circular structure
#' cov_mat <- covMatC(p = p, rho = rho)
#' data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
#' indTest(data)
#' indTest(data, covMat = cov_mat)
#'
#'
#' @export
#' @importFrom stats cov var pchisq
indTest <- function(X, covMat = NULL, alpha = 0.05) {
n <- nrow(X)
p <- ncol(X)
# Maximum likelihood estimator of covariance matrix
A <- (n - 1) * stats::cov(X)
if (is.null(covMat)) {
covMat = stats::cov(X)
}
off_diag <- covMat[!row(covMat) == col(covMat)]
if (any(off_diag > 0) && any(off_diag < 0)) {
cat("Alert:")
cat('\n')
cat("The off-diagonal elements of the covariance matrix are not the same signs. The results may not be reliable.")
cat("\n")
}
# Check if the covariance matrix is symmetric
if (!isSymmetric(covMat)) {
stop("Covariance matrix is not symmetric.")
}
sig <- diag(cov(X))
W <- rowSums(X)
if (is.null(covMat)) {
# Sigma unknown
test_statistic <- (n - 1) * stats::var(W) / sum(sig)
df <- n - 1
} else {
# Sigma known
test_statistic <- (n - 1) * stats::var(W) / sum(diag(covMat))
df <- n - 1
}
# Calculate p-values for both tails
p_values_upper <- stats::pchisq(test_statistic, df = df, lower.tail = FALSE)
p_values_lower <- stats::pchisq(test_statistic, df = df, lower.tail = TRUE)
# Calculate final p-value using the minimum of probabilities
p_value <- 2 * min(p_values_upper, p_values_lower)
# Create a data frame to store results
result <- data.frame(Test_Statistic = test_statistic,
Degrees_of_Freedom = df,
Alpha = alpha,
P_Value = p_value,
Test_Result = ifelse(p_value <= alpha, "Reject H0", "Fail to Reject H0"))
return(result)
}
indTest(data)
indTest(data, covMat = cov_mat)
#' # Covariance structure with Circular structure
cov_mat <- covMatC(p = p, rho = rho)
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
indTest(data)
indTest(data, covMat = cov_mat)
cov_mat
n = 10 # Sample Size
p = 20 # number of variables
rho = 0.014
# Covariance structure with Autoregressive structure
cov_mat <- covMatAR(p = p, rho = rho)
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
data
indTest(data)
rho = 0.4
# Covariance structure with Autoregressive structure
cov_mat <- covMatAR(p = p, rho = rho)
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
indTest(data)
indTest(data)
cov_mat)
cov_mat
rho = 0.9
# Covariance structure with Autoregressive structure
cov_mat <- covMatAR(p = p, rho = rho)
cov_mat
rho = 0.4
# Covariance structure with Autoregressive structure
cov_mat <- covMatAR(p = p, rho = rho)
cov_mat
cov_mat
cov_mat <- covMatAR(p = p, rho = rho)
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
indTest(data)
indTest(data)
cov(data)
indTest(data, covMat = cov_mat)
usethis::use_git_config(user.name = "YourName", user.email = "[email protected]")
install.packages("usethis")
library(usethis)
usethis::use_git_config(user.name = "fjmmarques", user.email = "[email protected]")
n = 50 # Sample Size
p = 5 # number of variables
rho = 0.4
# Covariance structure with Autoregressive structure
cov_mat <- covMatAR(p = p, rho = rho)
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
indTest(data)
indTest(data, covMat = cov_mat)
# data with missing vales
missing_rate <- 0.1 # 10% missing values
missing_index_row <- sample(1:n, size = round(n * missing_rate))
missing_index_col <- sample(1:p, size = 1)
data[missing_index_row, missing_index_col] <- NA # Introduce missing values
indTest(data)
indTest(data, covMat = cov_mat)
# data with missing vales
missing_rate <- 0.1 # 10% missing values
missing_index_row <- sample(1:n, size = round(n * missing_rate))
missing_index_col <- sample(1:p, size = 1)
data[missing_index_row, missing_index_col] <- NA # Introduce missing values
indTest(data)
#'
#' #' # Covariance structure with Circular structure
#' cov_mat <- covMatC(p = p, rho = rho)
#' data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
#' indTest(data)
#' indTest(data, covMat = cov_mat)
#'
#'
#' @export
#' @importFrom stats cov var pchisq
indTest <- function(X, covMat = NULL, alpha = 0.05) {
if (any(is.na(X))) {
cat("Alert:")
cat('\n')
cat("The data has missing values. The missing values are handled by casewise deletion (and if there are no complete cases, that gives an error)")
cat("\n")
# [We should discuss the following]
# cov(X, use = 'complete.ons')
X <- data.frame(na.omit(X))
}
n <- nrow(X)
p <- ncol(X)
# Maximum likelihood estimator of covariance matrix
A <- (n - 1) * stats::cov(X)
if (is.null(covMat)) {
covMat = stats::cov(X)
}
off_diag <- covMat[!row(covMat) == col(covMat)]
if (any(off_diag > 0) && any(off_diag < 0)) {
cat("Alert:")
cat('\n')
cat("The off-diagonal elements of the covariance matrix are not the same signs. The results may not be reliable.")
cat("\n")
}
# Check if the covariance matrix is symmetric
if (!isSymmetric(covMat)) {
stop("Covariance matrix is not symmetric.")
}
sig <- diag(cov(X))
W <- rowSums(X)
if (is.null(covMat)) {
# Sigma unknown
test_statistic <- (n - 1) * stats::var(W) / sum(sig)
df <- n - 1
} else {
# Sigma known
test_statistic <- (n - 1) * stats::var(W) / sum(diag(covMat))
df <- n - 1
}
# Calculate p-values for both tails
p_values_upper <- stats::pchisq(test_statistic, df = df, lower.tail = FALSE)
p_values_lower <- stats::pchisq(test_statistic, df = df, lower.tail = TRUE)
# Calculate final p-value using the minimum of probabilities
p_value <- 2 * min(p_values_upper, p_values_lower)
# Create a data frame to store results
result <- data.frame(Test_Statistic = test_statistic,
Degrees_of_Freedom = df,
Alpha = alpha,
P_Value = p_value,
Test_Result = ifelse(p_value <= alpha, "Reject H0", "Fail to Reject H0"))
return(result)
}
#'
#' #' # Covariance structure with Circular structure
#' cov_mat <- covMatC(p = p, rho = rho)
#' data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
#' indTest(data)
#' indTest(data, covMat = cov_mat)
#'
#'
#' @export
#' @importFrom stats cov var pchisq
indTest <- function(X, covMat = NULL, alpha = 0.05) {
if (any(is.na(X))) {
cat("Alert:")
cat('\n')
cat("The data has missing values. The missing values are handled by casewise deletion (and if there are no complete cases, that gives an error)")
cat("\n")
# [We should discuss the following]
# cov(X, use = 'complete.ons')
X <- data.frame(na.omit(X))
}
n <- nrow(X)
p <- ncol(X)
# Maximum likelihood estimator of covariance matrix
A <- (n - 1) * stats::cov(X)
if (is.null(covMat)) {
covMat = stats::cov(X)
}
off_diag <- covMat[!row(covMat) == col(covMat)]
if (any(off_diag > 0) && any(off_diag < 0)) {
cat("Alert:")
cat('\n')
cat("The off-diagonal elements of the covariance matrix are not the same signs. The results may not be reliable.")
cat("\n")
}
# Check if the covariance matrix is symmetric
if (!isSymmetric(covMat)) {
stop("Covariance matrix is not symmetric.")
}
sig <- diag(cov(X))
W <- rowSums(X)
if (is.null(covMat)) {
# Sigma unknown
test_statistic <- (n - 1) * stats::var(W) / sum(sig)
df <- n - 1
} else {
# Sigma known
test_statistic <- (n - 1) * stats::var(W) / sum(diag(covMat))
df <- n - 1
}
# Calculate p-values for both tails
p_values_upper <- stats::pchisq(test_statistic, df = df, lower.tail = FALSE)
p_values_lower <- stats::pchisq(test_statistic, df = df, lower.tail = TRUE)
# Calculate final p-value using the minimum of probabilities
p_value <- 2 * min(p_values_upper, p_values_lower)
# Create a data frame to store results
result <- data.frame(Test_Statistic = test_statistic,
Degrees_of_Freedom = df,
Alpha = alpha,
P_Value = p_value,
Test_Result = ifelse(p_value <= alpha, "Reject H0", "Fail to Reject H0"))
return(result)
}
library(MASS)
n = 50 # Sample Size
p = 5 # number of variables
rho = 0.4
# Covariance structure with Autoregressive structure
cov_mat <- covMatAR(p = p, rho = rho)
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
indTest(data)
indTest(data, covMat = cov_mat)
# data with missing vales
missing_rate <- 0.1 # 10% missing values
missing_index_row <- sample(1:n, size = round(n * missing_rate))
missing_index_col <- sample(1:p, size = 1)
data[missing_index_row, missing_index_col] <- NA # Introduce missing values
indTest(data)
indTest(data, covMat = cov_mat)
# Covariance structure with Compound Symmetry structure
cov_mat <- covMatCS(p = p, rho = rho)
data <- mvrnorm(n = n, mu = rep(0,p), Sigma = cov_mat)
indTest(data)
indTest(data, covMat = cov_mat)
# install.packages("ggplot2")
# install.packages("maps")
library(ggplot2)
library(maps)
# Import the data with coordinates
world <- map_data("world")
# Plot the map. group = group connects the points in the correct order
ggplot(data = world, aes(x = long, y = lat, group = group)) +
geom_polygon()
# Import the data with coordinates
world <- map_data("portugal")
# Plot the map. group = group connects the points in the correct order
ggplot(data = port, aes(x = long, y = lat, group = group)) +
geom_polygon()
# Import the data with coordinates
port <- map_data("portugal")
# Import the data with coordinates
port <- map_data("port")
# install.packages("ggplot2")
# install.packages("maps")
library(ggplot2)
library(maps)
#Add the data to the shapefile
europe_df <- europe %>% left_join(df, by=c("name_long" ="Country"))
#Add the data to the shapefile
europe_df <- europe %>% left_join(df, by=c("name_long" ="Portugal"))
#Add the data to the shapefile
europe_df <-left_join(df, by=c("name_long" ="Portugal"))
library(maps)
library(ggplot2)
## make a df with only the country to overlap
map_data_es <- map_data('world')[map_data('world')$region == "Spain",]
## The map (maps + ggplot2 )
ggplot() +
## First layer: worldwide map
geom_polygon(data = map_data("world"),
aes(x=long, y=lat, group = group),
color = '#9c9c9c', fill = '#f3f3f3') +
## Second layer: Country map
geom_polygon(data = map_data_es,
aes(x=long, y=lat, group = group),
color = 'red', fill = 'pink') +
coord_map() +
coord_fixed(1.3,
xlim = c(-13.5, 8.5),
ylim = c(34, 45)) +
ggtitle("A map of Spain") +
theme(panel.background =element_rect(fill = 'blue'))
## make a df with only the country to overlap
map_data_es <- map_data('world')[map_data('world')$region == "Portugal",]
## make a df with only the country to overlap
map_data_es <- map_data('world')[map_data('world')$region == "Portugal",]
## The map (maps + ggplot2 )
ggplot() +
## First layer: worldwide map
geom_polygon(data = map_data("world"),
aes(x=long, y=lat, group = group),
color = '#9c9c9c', fill = '#f3f3f3') +
## Second layer: Country map
geom_polygon(data = map_data_es,
aes(x=long, y=lat, group = group),
color = 'red', fill = 'pink') +
coord_map() +
coord_fixed(1.3,
xlim = c(-13.5, 8.5),
ylim = c(34, 45)) +
ggtitle("A map of Spain") +
theme(panel.background =element_rect(fill = 'blue'))
## make a df with only the country to overlap
map_data_es <- map_data('portugal')[map_data('world')$region == "Portugal",]