jmbm

Fig_09

Oct 10th, 2022 (edited)
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 1.85 KB | None | 0 0
  1. pdf("fig_09.pdf", width = 8, height = 5)
  2. par(bty = "n", las = 1, mar = c(3, 6, 1, 1) + 0.2, mgp = c(5, 1, 0))
  3.  
  4. # función suma armónicos
  5. sum_arm <- function(n) {
  6.   a <- numeric(n)
  7.   for (i in 1:n) {
  8.     for (j in 1:i) {
  9.       a[j] <- a[j] + 1/i
  10.     }
  11.   }
  12.   a/n
  13. }
  14.  
  15. # función para contar la ocurrencia de una letra
  16. cuentaletras <- function(letra, texto) {
  17.   texto2 <- gsub(letra, "", texto, ignore.case = TRUE)
  18.   return (nchar(texto) - nchar(texto2))
  19. }
  20. # cargamos el libro en una cadena gigante
  21. libro <- readChar("quijote.txt", file.info("quijote.txt")$size)
  22. # quitamos saltos de línea
  23. libro <- gsub("\n", "", libro)
  24. # quitamos las tildes y diéresis
  25. libro <- chartr("áéíóúàèìòùäëïöüÁÉÍÓÚÀÈÌÒÙÄËÏÖÜ", "aeiouaeiouaeiouAEIOUAEIOUAEIOU", libro)
  26. # abecedario
  27. abecedario <- "abcdefghijklmnñopqrstuvwxyz"
  28. # contaje y resultado
  29. for (i in 1:27) {
  30.   letra <- substr(abecedario, i, i)
  31.   cuenta <- cuentaletras(letra, libro)
  32.   cat(letra, ": ", cuenta, "\n")
  33. }
  34.  
  35. # datos
  36. obs <- c(229147, 200466, 162480, 125701, 108415, 100932, 90055, 89125, 87230, 79550, 61734, 59425,  44649, 35451, 32478, 25107, 24142, 19916, 17855, 17224, 10530, 7581, 6490, 4241, 377, 2)
  37. nomb <- c("e", "a", "o", "s", "n", "r", "i", "l", "d", "u", "t", "c", "m", "p", "q", "y", "b", "h", "v", "g", "j", "f", "z", "ñ", "x", "w")
  38. n <- length(obs)
  39. teor <- sum(obs)*sum_arm(n)
  40.  
  41. R2 <- 1 - sum((obs - teor)^2) / var(obs) / (n - 1)
  42.  
  43. # gráfico
  44. plot(1:n - 0.1, obs, ylab = "Número de veces", type = "h", las = 2, ylim = c(0, 250000), lwd = 2, xlab = "", xaxt = "n")
  45. axis(1, at = 1:n, labels = nomb, las = 1, cex.axis = 0.8)
  46. lines(1:n + 0.1, teor, type = "h", col = "red", lwd = 2)
  47. legend("topright", bty = "n", cex = 0.8, c("observado", "teórico"), lty = 1, lwd = 2, col = c("black", "red"))
  48. text(16, 160000, bquote(R^2 ~ ":" ~ .(round(R2, 2))))
  49.  
  50. dev.off()
Advertisement
Add Comment
Please, Sign In to add comment