Advertisement
Guest User

Untitled

a guest
Aug 29th, 2014
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. setClass(
  2. class = "lreg5"
  3. , representation = representation(
  4. coefficients="numeric"
  5. , var="matrix"
  6. , deviance="numeric"
  7. , predictors="character"
  8. , iterations="numeric"
  9. )
  10. )
  11.  
  12. lreg5 <-
  13. function(X, y, predictors=colnames(X), max.iter=10,
  14. tol=1E-6, constant=TRUE, ...) {
  15. if (!is.numeric(X) || !is.matrix(X))
  16. stop("X must be a numeric matrix")
  17. if (!is.numeric(y) || !all(y == 0 | y == 1))
  18. stop("y must contain only 0s and 1s")
  19. if (nrow(X) != length(y))
  20. stop("X and y contain different numbers of observations")
  21. if (constant) {
  22. X <- cbind(1, X)
  23. colnames(X)[1] <- "Constant"
  24. }
  25. b <- b.last <- rep(0, ncol(X))
  26. it <- 1
  27. while (it <= max.iter){
  28. p <- as.vector(1/(1 + exp(-X %*% b)))
  29. var.b <- solve(crossprod(X, p * (1 - p) * X))
  30. b <- b + var.b %*% crossprod(X, y - p)
  31. if (max(abs(b - b.last)/(abs(b.last) + 0.01*tol)) < tol) break
  32. b.last <- b
  33. it <- it + 1
  34. }
  35. if (it > max.iter) warning("maximum iterations exceeded")
  36. dev <- -2*sum(y*log(p) + (1 - y)*log(1 - p))
  37. result <- new("lreg5", coefficients=as.vector(b), var=var.b,
  38. deviance=dev, predictors=predictors, iterations=it)
  39. result
  40. }
  41.  
  42. setMethod("show", signature(object="lreg5"),
  43. definition=function(object) {
  44. coef <- object@coefficients
  45. names(coef) <- object@predictors
  46. print(coef)
  47. }
  48. )
  49.  
  50.  
  51. setMethod("summary", signature(object="lreg5"),
  52. definition=function(object, ...) {
  53. b <- object@coefficients
  54. se <- sqrt(diag(object@var))
  55. z <- b/se
  56. table <- cbind(b, se, z, 2*(1-pnorm(abs(z))))
  57. colnames(table) <- c("Estimate", "Std.Err", "Z value", "Pr(>z)")
  58. rownames(table) <- object@predictors
  59. printCoefmat(table)
  60. cat("nDeviance =", object@deviance,"n")
  61. }
  62. )
  63.  
  64. # Step 0: Packages you will need
  65. library(devtools)
  66. library(roxygen2)
  67.  
  68. # Step 1: Create your package directory
  69. setwd("WD")
  70.  
  71. create("PackageName")
  72.  
  73.  
  74. # Step 2: Add functions
  75.  
  76. # Step 3: Add documentation
  77.  
  78. # Step 4: Process your documentation
  79. setwd("./PackageName")
  80. devtools::document()
  81.  
  82. # Step 5: Install!
  83. setwd("..")
  84. #load_all("PackageName")
  85. devtools::install("PackageName")
  86.  
  87. # Stp 6: Load the Package!
  88. library(PackageName)
  89. help(PackageName)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement