###### R-Script zu Korrellation ######
#
# (c) Dr. Matthias Gottlieb, 2026
# kontakt@goitsystems.de
#
# GoITSystems: Korrelationsstudie mit R
# Speichere diese Datei als UTF-8. Fuehre sie in RStudio mit Source aus.
# Keine Zusatzpakete erforderlich.
# Alle Daten sind synthetisch. Keine Replikation von Davis (1989).

output_dir <- file.path(getwd(), "correlation_study_output")
dir.create(output_dir, recursive = TRUE, showWarnings = FALSE)
if (!capabilities("png")) stop("Diese R-Installation unterstuetzt keinen PNG-Export.")

# 1. Synthetisches WI-Beispiel erzeugen.
# Beide Variablen sind dimensionslose Simulationsindizes.
# Sie sind weder validierte Skalenwerte noch echte Befragungsdaten.
RNGkind(kind = "Mersenne-Twister", normal.kind = "Inversion", sample.kind = "Rejection")
set.seed(42)
sample_size <- 120L
population_rho <- 0.55
perceived_usefulness <- rnorm(sample_size)
usage_intention <- population_rho * perceived_usefulness +
  sqrt(1 - population_rho^2) * rnorm(sample_size)
study_data <- data.frame(
  participant_id = seq_len(sample_size),
  perceived_usefulness = perceived_usefulness,
  usage_intention = usage_intention
)
write.csv(study_data, file.path(output_dir, "correlation_study_data.csv"), row.names = FALSE)
saveRDS(study_data, file.path(output_dir, "correlation_study_data.rds"))

# 2. Die exportierten Daten wieder einlesen und pruefen.
study_data <- read.csv(file.path(output_dir, "correlation_study_data.csv"))
stopifnot(nrow(study_data) == sample_size,
          !anyDuplicated(study_data$participant_id),
          all(is.finite(study_data$perceived_usefulness)),
          all(is.finite(study_data$usage_intention)),
          sd(study_data$perceived_usefulness) > 0,
          sd(study_data$usage_intention) > 0)

# 3. Pearson und Spearman fuer die identischen Wertepaare berechnen.
# Die Simulation erzeugt unabhaengige, bivariat normale Paare.
# rho ist ein Simulationsparameter. Das Stichproben-r kann davon abweichen.
pearson_test <- cor.test(study_data$perceived_usefulness,
                         study_data$usage_intention,
                         method = "pearson", alternative = "two.sided",
                         conf.level = 0.95)
spearman_test <- cor.test(study_data$perceived_usefulness,
                          study_data$usage_intention,
                          method = "spearman", alternative = "two.sided",
                          exact = FALSE)
# cor.test liefert hier nur fuer Pearson ein Konfidenzintervall.
results <- data.frame(
  method = c("Pearson", "Spearman"),
  n = nrow(study_data),
  estimate = c(unname(pearson_test$estimate), unname(spearman_test$estimate)),
  conf_low = c(pearson_test$conf.int[1], NA_real_),
  conf_high = c(pearson_test$conf.int[2], NA_real_),
  p_value = c(pearson_test$p.value, spearman_test$p.value),
  inference = c("two-sided; Fisher-z confidence interval",
                "two-sided; asymptotic p-value; no CI computed")
)
write.csv(results, file.path(output_dir, "correlation_results.csv"), row.names = FALSE)
capture.output(pearson_test, spearman_test,
               file = file.path(output_dir, "correlation_tests.txt"))

# 4. Sprachabhaengige Texte.
labels <- list(
  de = list(
    title = "Korrelationsstudie: Beispiel aus der Wirtschaftsinformatik",
    x = "Wahrgenommene Nützlichkeit\n(synthetischer Index; dimensionslos)",
    y = "Nutzungsabsicht\n(synthetischer Index; dimensionslos)",
    synthetic = "Synthetische Daten. Keine Befragung. Keine validierten Messskalen.",
    caution = "Der vorgegebene Zusammenhang ist kein empirischer Befund oder Kausalnachweis.",
    source = "Methodische Grundlage: Schober et al. (2018), doi:10.1213/ANE.0000000000002864",
    creation = "Mit KI-Unterstützung erstellt.",
    patterns_title = "Pearson-Korrelation: Vier mögliche Datenmuster",
    panel = c("A: Positiver linearer Zusammenhang", "B: Negativer linearer Zusammenhang",
              "C: Unabhängig erzeugte Werte", "D: U-förmiger Zusammenhang"),
    px = "Merkmal X (dimensionslos)", py = "Merkmal Y (dimensionslos)",
    pattern_note = "Ein Pearson-r nahe null schließt nichtlineare Zusammenhänge nicht aus.",
    pattern_data = "Eigene Darstellung mit synthetischen Daten. Keine empirischen Studienergebnisse."
  ),
  en = list(
    title = "Correlation study: An information systems example",
    x = "Perceived usefulness\n(synthetic index; dimensionless)",
    y = "Usage intention\n(synthetic index; dimensionless)",
    synthetic = "Synthetic data. No survey. No validated measurement scales.",
    caution = "The specified association is not an empirical finding or evidence of causation.",
    source = "Methodological basis: Schober et al. (2018), doi:10.1213/ANE.0000000000002864",
    creation = "Created with AI assistance.",
    patterns_title = "Pearson correlation: Four possible data patterns",
    panel = c("A: Positive linear association", "B: Negative linear association",
              "C: Independently generated values", "D: U-shaped association"),
    px = "Variable X (dimensionless)", py = "Variable Y (dimensionless)",
    pattern_note = "A Pearson r near zero does not rule out nonlinear associations.",
    pattern_data = "Original illustration using synthetic data. No empirical study results."
  )
)
num <- function(value, language, digits = 2L) {
  if (abs(value) < 0.5 * 10^(-digits)) value <- 0
  formatC(value, format = "f", digits = digits,
          decimal.mark = if (language == "de") "," else ".")
}
open_png <- function(filename, width, height) {
  args <- list(filename = filename, width = width, height = height,
               units = "px", res = 240, pointsize = 12, bg = "white")
  if (capabilities("cairo")) args$type <- "cairo"
  do.call(grDevices::png, args)
}
point_color <- "#20577D"

# 5. WI-Streudiagramm als deutsche und englische PNG-Datei exportieren.
plot_study <- function(language) {
  lab <- labels[[language]]
  filename <- file.path(output_dir, paste0("correlation_study_example_", language, ".png"))
  open_png(filename, 3000, 2400)
  on.exit(dev.off(), add = TRUE)
  par(mar = c(7.7, 6.4, 4.6, 1.6), family = "sans", las = 1)
  plot(study_data$perceived_usefulness, study_data$usage_intention,
       type = "n", xlab = "", ylab = "", main = "", cex.axis = 1)
  grid(col = "#E3E8ED")
  points(study_data$perceived_usefulness, study_data$usage_intention,
         pch = 19, cex = 0.85, col = adjustcolor(point_color, alpha.f = 0.75))
  title(main = lab$title, line = 2.7, cex.main = 1.05)
  title(sub = paste0("n = ", nrow(study_data),
                     " | Pearson r = ", num(pearson_test$estimate, language),
                     " | Spearman rho = ", num(spearman_test$estimate, language)),
        line = 4.3, cex.sub = 0.9)
  mtext(lab$x, side = 1, line = 2.6, cex = 0.95)
  mtext(lab$y, side = 2, line = 3.6, las = 0, cex = 0.95)
  mtext(lab$synthetic, side = 1, line = 5.3, cex = 0.70)
  mtext(lab$caution, side = 1, line = 6.0, cex = 0.67)
  mtext(lab$source, side = 1, line = 6.65, cex = 0.60)
  mtext(lab$creation, side = 1, line = 7.3, cex = 0.60)
  invisible(filename)
}

# 6. Vier Datenmuster mit einheitlicher Skalierung erzeugen.
# Kein Hypothesentest: Das feste x-Raster dient nur der Illustration.
set.seed(42)
pattern_n <- 80L
x <- seq(-2, 2, length.out = pattern_n)
pattern_data <- rbind(
  data.frame(pattern = "A", x = x, y = x + rnorm(pattern_n, 0, 0.6)),
  data.frame(pattern = "B", x = x, y = -x + rnorm(pattern_n, 0, 0.6)),
  data.frame(pattern = "C", x = x, y = rnorm(pattern_n)),
  data.frame(pattern = "D", x = x, y = x^2 - mean(x^2))
)
write.csv(pattern_data, file.path(output_dir, "correlation_patterns_data.csv"), row.names = FALSE)
pattern_results <- do.call(rbind, lapply(c("A", "B", "C", "D"), function(key) {
  d <- pattern_data[pattern_data$pattern == key, ]
  data.frame(pattern = key, n = nrow(d), pearson_r = cor(d$x, d$y))
}))
stopifnot(all(pattern_results$n == pattern_n),
          abs(pattern_results$pearson_r[pattern_results$pattern == "D"]) < 1e-12)
write.csv(pattern_results, file.path(output_dir, "correlation_patterns_results.csv"), row.names = FALSE)
plot_patterns <- function(language) {
  lab <- labels[[language]]
  filename <- file.path(output_dir, paste0("correlation_patterns_", language, ".png"))
  open_png(filename, 3200, 2800)
  on.exit(dev.off(), add = TRUE)
  par(mfrow = c(2, 2), mar = c(4.4, 4.5, 3.6, 1.0),
      oma = c(5.2, 0, 3.0, 0), family = "sans", las = 1)
  y_limits <- extendrange(pattern_data$y, f = 0.08)
  for (i in seq_len(nrow(pattern_results))) {
    key <- pattern_results$pattern[i]
    d <- pattern_data[pattern_data$pattern == key, ]
    plot(d$x, d$y, xlim = c(-2.2, 2.2), ylim = y_limits,
         type = "n", xlab = "", ylab = "", main = "", cex.axis = 0.9)
    grid(col = "#E3E8ED")
    points(d$x, d$y, pch = 19, cex = 0.65,
           col = adjustcolor(point_color, alpha.f = 0.8))
    title(main = lab$panel[i], line = 2.0, cex.main = 0.90)
    mtext(paste0("Pearson r = ", num(pattern_results$pearson_r[i], language),
                 " | n = ", pattern_n), side = 3, line = 0.7, cex = 0.8)
    mtext(lab$px, side = 1, line = 2.5, cex = 0.85)
    mtext(lab$py, side = 2, line = 3, las = 0, cex = 0.85)
  }
  mtext(lab$patterns_title, side = 3, outer = TRUE, line = 1.0, cex = 1.1, font = 2)
  mtext(lab$pattern_note, side = 1, outer = TRUE, line = 0.5, cex = 0.85)
  mtext(lab$pattern_data, side = 1, outer = TRUE, line = 1.6, cex = 0.75)
  mtext(lab$source, side = 1, outer = TRUE, line = 2.7, cex = 0.65)
  mtext(lab$creation, side = 1, outer = TRUE, line = 3.8, cex = 0.65)
  invisible(filename)
}

for (language in c("de", "en")) {
  plot_study(language)
  plot_patterns(language)
}

# 7. Softwareumgebung und Variablenbeschreibung sichern.
capture.output(sessionInfo(), file = file.path(output_dir, "session_info.txt"))
writeLines(c(
  "All data are synthetic. No survey was conducted.",
  "participant_id: unique synthetic case identifier.",
  "perceived_usefulness: dimensionless normal simulation index; not a validated scale.",
  "usage_intention: dimensionless normal simulation index; not a validated scale.",
  "Both variables have population mean 0 and variance 1 by construction.",
  "Their sample means and standard deviations need not equal 0 and 1.",
  "population_rho = 0.55 specifies association, not a causal mechanism.",
  "The index values are unbounded. They are not responses on a 1-7 scale.",
  "The example illustrates analysis. It cannot validate an IS theory.",
  "Schober et al. (2018): https://doi.org/10.1213/ANE.0000000000002864",
  "R cor.test: https://stat.ethz.ch/R-manual/R-devel/library/stats/html/cor.test.html"
), file.path(output_dir, "data_dictionary.txt"), useBytes = TRUE)

expected_png <- file.path(output_dir, c(
  "correlation_study_example_de.png", "correlation_study_example_en.png",
  "correlation_patterns_de.png", "correlation_patterns_en.png"))
stopifnot(all(file.exists(expected_png)), all(file.info(expected_png)$size > 0))
message("Export abgeschlossen: ", normalizePath(output_dir))
print(results)

