Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. bael_calib <- function(formula = waga ~ plec:klm2:grwiek1 | idm + lp | msc,
  2. data,
  3. totals,
  4. method = 'linear',
  5. bounds = c(0,10)) {
  6.  
  7. fm1 <- as.Formula(formula)
  8.  
  9. vars_weight <- attr(fm1, 'lhs')[[1]]
  10. vars_calib <- attr(fm1, 'rhs')[[1]]
  11. vars_ids <- attr(fm1, 'rhs')[[2]]
  12. vars_split <- as.character(attr(fm1, 'rhs')[[3]])
  13.  
  14.  
  15. vars_calib <- unlist(strsplit(paste(vars_calib), '\\+|\\*|:'))
  16. vars_calib <- vars_calib[nchar(vars_calib) > 0]
  17.  
  18. vars_ids <- unlist(strsplit(paste(vars_ids), '\\+|\\*|:'))
  19. vars_ids <- vars_ids[nchar(vars_ids) > 0]
  20.  
  21. ## tworzenie zmiennych 0-1 -- na podstawie
  22. setkeyv(data, c(vars_split)) ## dla przyspieszenia
  23.  
  24. data[, aux_x := Reduce(function(...) paste0(...), .SD), .SDcols = vars_calib]
  25. data[, ids := Reduce(function(...) paste0(...), .SD), .SDcols = vars_ids]
  26.  
  27. ## dane do kalibracji
  28. aux <- data[, list(aux = list(t(fac2sparse(aux_x))),
  29. ids = list(ids)),
  30. by = c(vars_split)]
  31.  
  32. d <- data[, list(d = list(as.numeric(unlist(.SD)))),
  33. by = c(vars_split),
  34. .SDcols = as.character(vars_weight)]
  35.  
  36. totals <- totals[, list(pop = list(pop)),
  37. by = c(vars_split)]
  38.  
  39. do_kalibracji <- totals[d[aux,
  40. on = vars_split],
  41. on = vars_split]
  42. ## test czy długości totali i wymiary X są równe
  43. do_kalibracji[,flag:=length(pop[[1]])==ncol(aux[[1]]),
  44. by = c(vars_split)]
  45.  
  46. method_no <- length(method)
  47.  
  48. if (method_no == 1) {
  49. po_kalib <- do_kalibracji[flag == TRUE,
  50. list(g = list(calibWeights2(d = d[[1]],
  51. X = aux[[1]],
  52. totals = pop[[1]],
  53. method = method,
  54. bounds = bounds)),
  55. ids = list(ids[[1]])),
  56. by = c(vars_split)]
  57.  
  58. result <- po_kalib[,list(g = unlist(g),
  59. ids = unlist(ids)),
  60. by = c(vars_split)]
  61. } else {
  62. po_kalib <- list()
  63. for (m in method) {
  64. po_kalib[[m]] <- do_kalibracji[flag == TRUE,
  65. list(g = list(calibWeights2(d = d[[1]],
  66. X = aux[[1]],
  67. totals = pop[[1]],
  68. method = m,
  69. bounds = bounds)),
  70. ids = list(ids[[1]])),
  71. by = c(vars_split)]
  72.  
  73. po_kalib_ <- lapply(po_kalib, function(x) {
  74. x[,list(g = unlist(g),
  75. ids = unlist(ids)),
  76. by = c(vars_split)]
  77. })
  78. result <- rbindlist(po_kalib_,idcol = 'method')
  79. }
  80. }
  81. return(result)
  82.  
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement