Für Vorlesungen, bitte die Webseite verwenden. https://flavigny.de/lecture
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

84 satır
2.1KB

  1. # Welche der beiden Sequenzen entstammt einem fairen Münzwurf (mit unabhängigen Würfe)?
  2. x <- c(1,1,1,0,1,0,0,1,1,1,0,1,0,0,1,1,0,1,1,1,
  3. 0,0,0,0,0,0,1,1,1,1,1,1,0,0,1,0,0,1,0,0,
  4. 1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,0,1,1,0,0,
  5. 1,0,1,0,0,1,1,0,1,1,0,1,0,0,0,0,0,0,0,0,
  6. 1,0,1,0,1,0,0,0,1,0,1,0,1,1,1,1,0,0,1,1)
  7. y <- c(1,0,1,0,1,1,0,1,0,0,1,1,0,0,0,1,0,1,1,1,
  8. 0,0,1,1,0,0,1,0,1,1,0,1,0,1,0,1,1,0,1,0,
  9. 0,1,0,1,0,0,1,0,0,1,1,1,0,1,0,1,0,1,0,1,
  10. 0,1,0,1,1,0,1,0,1,0,0,1,0,0,0,1,0,0,1,1,
  11. 0,1,0,0,0,1,1,0,0,1,0,1,0,0,1,0,1,0,1,1)
  12. c(length(x), length(y)) # gleiche Länge
  13. table(x) # zähle Anzahl der 1en und 0en
  14. table(y)
  15. get_runs_statistic <- function(v) {
  16. r <- rle(v)
  17. c(number_of_runs = length(r$lengths),
  18. longest_run = max(r$lengths),
  19. number_of_ones = sum(v == 1))
  20. }
  21. get_confidence_region <- function(v, alpha) {
  22. stopifnot(length(alpha)==1)
  23. q <- 1 - alpha
  24. stopifnot(q > 0 && q <= 1)
  25. i <- 0
  26. m <- mean(v)
  27. while(
  28. sum(m-i <= v & v <= m+i) / length(v) < q
  29. ) i <- i+0.5
  30. return(list(left=ceiling(m-i)-0.5, right=floor(m+i)+0.5))
  31. }
  32. n <- length(x)
  33. rx <- get_runs_statistic(x)
  34. ry <- get_runs_statistic(y)
  35. # simulate fair coin tosses
  36. library(tibble)
  37. set.seed(0)
  38. simu <- replicate(1e5, # execute following function call 1e5 times
  39. get_runs_statistic(sample(0:1, n, replace=TRUE)))
  40. data <- as_tibble(t(simu))
  41. # Plot results
  42. layout(
  43. rbind(
  44. c(1, 2),
  45. c(3, 3)
  46. ),
  47. heights=c(1, 1),
  48. )
  49. clrs <- list(x = "red", y = "blue", conf = "#00FF0040")
  50. mark_lwd <- 3
  51. invisible(lapply(names(data), function (nm) {
  52. v <- data[[nm]]
  53. hist(v, breaks=(min(v)-0.5):(max(v)+0.5), main=nm, xlab=NULL)
  54. y_axis_max <- par("yaxp")[2]
  55. segments(rx[nm], 0, y1=y_axis_max, col=clrs$x, lwd=mark_lwd)
  56. segments(ry[nm], 0, y1=y_axis_max, col=clrs$y, lwd=mark_lwd)
  57. conf <- get_confidence_region(v, 0.05)
  58. rect(conf$left, 0, conf$right, y_axis_max, col=clrs$conf, border=NA)
  59. }))
  60. legend(
  61. "topright",
  62. c("x", "y", "95% confidence"),
  63. col=c(clrs$x, clrs$y, clrs$conf),
  64. lwd=mark_lwd)