File: 6A-VectorMatrixAddon.R

package info (click to toggle)
fmultivar 240.10068-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 1,492 kB
  • ctags: 272
  • sloc: fortran: 1,128; ansic: 764; sh: 22; makefile: 1
file content (744 lines) | stat: -rw-r--r-- 21,405 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744

# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU Library General 
# Public License along with this library; if not, write to the 
# Free Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
# MA  02111-1307  USA

# Copyrights (C)
# for this R-port: 
#   1999 - 2004, Diethelm Wuertz, GPL
#   Diethelm Wuertz <wuertz@itp.phys.ethz.ch>
#   info@rmetrics.org
#   www.rmetrics.org
# for the code accessed (or partly included) from other R-ports:
#   see R's copyright and license files
# for the code accessed (or partly included) from contributed R-ports
# and other sources
#   see Rmetrics's copyright file
    
    
################################################################################
# GENERATION:           DESCRIPTION:
#  matrix               R  Creates a matrix from the given set of values
#   diag                R  Creates a diagonal matrix or extracts diagonals
#   triang              M  Extracs the lower tridiagonal part from a matrix
#   Triang              M  Extracs the upper tridiagonal part from a matrix
#   pascal              M  Creates a Pascal matrix
#   colVec              M  Creates a column vector from a vector
#   rowVec              M  Creates a row vector from a vector
#  as.matrix            R  Attempts to turn its argument into a matrix     
#  is.matrix            R  Tests if its argument is a (strict) matrix
#  dimnames             R  Retrieves or sets the dimnames of an object
#  colnames|rownames    R  Retrieves or sets the row or column names 
#  colIds|rowIds        M  ... use alternatively
#  colIds<-|rowIds<-    M  ... for assignments
# SUBSETS:              DESCRIPTION:
#  dim                  R  Returns the dimension of a matrix object
#  ncol|nrow            R  Counts columns|rows of a matrix object
#  length               R  Counts elements of a matrix object
#   "["|"[["            R  Subsets a matrix object
#   (Arith)             R  Elementwise Arithmetic: + - * /
#   (Lops)              R  Elementwise logical Ops: > < >= <= == !=
#  cbind|rbind          R  Augments a matrix object by columns|rows
#  na.omit              R  Removes NA from a matrix object
# BASIC STATISTICS:     DESCRIPTION:
#  var                  R  returns the variance matrix
#  cov                  R  returns the covariance matrix
#  col|rowStats         B  calculates column|row statistics 
#   col|rowMeans        R  calculates column|row means
#   col|rowAvgs         B  calculates column|row averages
#   col|rowVars         B  calculates column|row variances
#   col|rowStdevs       B  calculates column|row standard deviations
#   col|rowSkewness     B  calculates column|row skewness 
#   col|rowKurtosis     B  calculates column|row kurtosis 
#   col|rowCumsums      B  calculates column|row cumulated sums 
# LINEAR ALGEBRA:       DESCRIPTION:
#  t                    R  returns the transposed matrix
#  det                  R  returns the determinant of a matrix
#  inv|chol2inv       M|R  returns the inverse of a matrix
#  norm                 M  returns the norm of a matrix
#  rk                   M  returns the rank of a matrix
#  tr                   M  returns the trace of a matrix
#  %*%                  R  returns the product of two matrices
#  %x%|kron           R|S  returns the Kronecker product
#  mexp                 M  computes the exponential of a square matrix
#  vec                  M  is the operator that stacks a matrix
#  vech                 M  is the operator that stacks the lower triangle
# MORE LINEAR ALGEBRA:  DESCRIPTION:
#  chol                 R  returns the Cholesky factor matrix
#  eigen                R  returns eigenvalues and eigenvectors
#  svd                  R  returns the singular value decomposition
#  kappa                R  returns the condition number of a matrix
#  qr                   R  returns the QR decomposition of a matrix
#  solve                R  solves a system of linear equations
#  backsolve            R  ... use when the matrix is upper triangular
#  forwardsolve         R  ... use when the matrix is lower triangular
# TIME SERIES           DESCRIPTION:
#  tslag                R  Lagged or leading vector/matrix of selected order(s)
#  .tslag1                 Internal Function used by tslag
#  pdl                  R  Regressor matrix for polynomial distributed lags  
################################################################################


################################################################################
# NOTES:
#  WHERE YOU FIND THE FUCTIONS?
#   R  Basic R Package
#   B  Rmetrics fBasics Package
#   M  This Rmetrics fMultivar Package
################################################################################


################################################################################
#  matrix               R  Creates a matrix from the given set of values
#   diag                R  Creates a diagonal matrix or extracts diagonals
#   triang              M  Extracs the lower tridiagonal part from a matrix
#   Triang              M  Extracs the upper tridiagonal part from a matrix
#   pascal              M  Creates a Pascal matrix
#   colVec              M  Creates a column vector from a vector
#   rowVec              M  Creates a row vector from a vector
#  as.matrix            R  Attempts to turn its argument into a matrix     
#  is.matrix            R  Tests if its argument is a (strict) matrix
#  dimnames             R  Retrieves or sets the dimnames of an object
#  colnames|rownames    R  Retrieves or sets the row or column names 
#  colIds|rowIds        M  ... use alternatively
#  colIds<-|rowIds<-    M  ... for assignments


triang = 
function(x) 
{   # A function implemented by Diethelm Wuertz
        
    # Description:
    #   Returns lower triangle matrix
        
    # FUNCTION:
    
    # Triangulate:
    x[row(x) < col(x)] = 0 
        
    # Return Value:
    x 
}
    

# ------------------------------------------------------------------------------

            
Triang = 
function(x) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns upper triangle matrix
    
    # FUNCTION:
    
    # Triangulate
    x[row(x) > col(x)] = 0 
    
    # Return Value:
    x 
} 
        

# ------------------------------------------------------------------------------


pascal = 
function(n) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Creates a Pascal matrix
    
    # Arguments:
    #   n - the dimension of the square matrix
    
    # Details:
    #   http://mathworld.wolfram.com/PascalMatrix.html
    #   Pascal matrices are symmetric and positive definite. 
    #   The determinant of a Pascal matrix is 1. 
    #   The inverse of a Pascal matrix has integer entries. 
    #   If lambda is an eigenvalue of a Pascal matrix, 
    #       then 1/lambda is also an eigenvalue of the matrix.
    #   The Cholesky factor of a Pascal matrix consists of 
    #       the elements of Pascals triangle
        
    # FUNCTION:
    
    # Pascal:
    N = n-1
    n.over.r = function(n, r) { 
        prod(1:n) / (prod(1:(n-r)) * prod(1:r) ) }
    X = rep(1, N)
    for ( i in 1:N )
        for ( j in 1:N )
        X = c(X, n.over.r(i+j, j))
        X = cbind(rep(1, N+1), matrix(X, byrow = TRUE, ncol = N))
        
    # Return Value:
    X 
}
 

# ------------------------------------------------------------------------------


colVec = 
function(x) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Converts a vector to a column vector
    
    # Details:
    #   A column vector is a matrix with one column.
    
    # Return Value:
    
    # FUNCTION:
    
    # Double Transpose:
    ans = t(t(x)) 
    
    # Return Value:
    ans
}
    

# ------------------------------------------------------------------------------


rowVec = 
function(x) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Converts a vector to a row vector
    
    # Details:
    #   A row vector is a matrix with one row.
    
    # FUNCTION:
    
    # Transpose:
    ans = t(x) 
    
    # Return Value:
    ans
}
    

# ------------------------------------------------------------------------------

       
colIds = 
function(x, ...) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Retrieves row names of a matrix-like object
    
    # FUNCTION:
    
    # Convert to Matrix
    x = as.matrix(x)
    
    # Return Value:
    colnames(x, ...) 
}
        

# ------------------------------------------------------------------------------

        
rowIds = 
function(x, ...) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Retrieves row names of a matrix-like object
    
    # FUNCTION:
    
    # Convert to Matrix
    x = as.matrix(x)
    
    # Return Value:
    rownames(x, ...) }
        

# ------------------------------------------------------------------------------


"colIds<-" = 
function(x, value)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Sets column names of a matrix-like object
    
    # FUNCTION:
    
    # Column Names:
    dn = dimnames(x)
    if(is.null(dn)) {
        if(is.null(value)) return(x)
        if((nd = length(dim(x))) < 2)
            stop("Object has less than two dimensions")
        dn = vector("list", nd)
    }
    if(length(dn) < 2)
        stop("Object has less than two dimensions")
    if(is.null(value)) dn[2] = list(NULL) else dn[[2]] = value
    dimnames(x) = dn
    
    # Return Value:
    x
}
 

# ------------------------------------------------------------------------------

       
"rowIds<-" = 
function(x, value) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Sets row names of a matrix-like object
    
    # FUNCTION:
    
    # Row names:
    dn = dimnames(x)
    if(is.null(dn)) {
        if(is.null(value)) return(x)
        if((nd = length(dim(x))) < 1)
            stop("attempt to set rownames on object with no dimensions")
        dn = vector("list", nd) }
    if(length(dn) < 1)
        stop("attempt to set rownames on object with no dimensions")
    if(is.null(value)) dn[1] = list(NULL) else dn[[1]] = value
    dimnames(x) = dn
    
    # Return Value:
    x
}


################################################################################
#  dim                  R  Returns the dimension of a matrix object
#  ncol|nrow            R  Counts columns|rows of a matrix object
#  length               R  Counts elements of a matrix object
#   "["|"[["            R  Subsets a matrix object
#   (Arith)             R  Elementwise Arithmetic: + - * /
#   (Lops)              R  Elementwise logical Ops: > < >= <= == !=
#  cbind|rbind          R  Augments a matrix object by columns|rows
#  na.omit              R  Removes NA from a matrix object


################################################################################
#  t                    R  returns the transposed matrix
#  det                  R  returns the determinant of a matrix
#  inv|chol2inv       M|R  returns the inverse of a matrix
#  norm                 M  returns the norm of a matrix
#  rk                   M  returns the rank of a matrix
#  tr                   M  returns the trace of a matrix
#  %*%                  R  returns the product of two matrices
#  %x%|kron           R|S  returns the Kronecker product
#  mexp                 M  computes the exponential of a square matrix
#  vec                  M  is the operator that stacks a matrix
#  vech                 M  is the operator that stacks the lower triangle


inv = 
function(x) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns the inverse of a matrix
    
    # FUNCTION:
    
    # Inverse:
    # ans = chol2inv(chol(x))
    # or ...
    ans = solve(x)
    
    # Return Value:
    ans 
}  


# ------------------------------------------------------------------------------


norm = 
function(x, p = 2) 
{   # A function implemented by Diethelm Wuertz
    
    # Description:
    #   Returns the spectral norm of a matrix
    
    # Details:
    #   http://mathworld.wolfram.com/MatrixNorm.html:
    #   For p = 1
    #       The maximum absolute column sum norm |A|_1 is defined 
    #       as the maximum of the sum of the absolute valued elements
    #       of columns of the matrix.
    #   For p = 2:
    #       The spectral |A|_2 norm is "the" of a matrix. This value
    #       is computed as the square root of the maximum eigenvalue   
    #       of A^H A where A^H is the conjugate transpose.
    #   For p = Inf:
    #       The maximum absolute row sum norm |A|_inf is defined 
    #       as the maximum of the sum of the absolute valued elements
    #       of rows of the matrix.

    # FUNCTION:
    
    # Compute Norm:
    ans = NA
    if (p == 1) {
        x = abs(x)
        ans = max(apply(x, 2, sum)) 
    }
    if (p == 2) {
        ans = sqrt(max(eigen(t(x) %*% x)$values))
    }
    if (p == Inf) {
        x = abs(x)
        ans = max(apply(x, 1, sum)) 
    }
    if (is.na(ans)) stop("Invalid value for p")
        
    # Return value:
    ans
}


# ------------------------------------------------------------------------------

        
rk = 
function(x, method = c("qr", "chol")) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns the rank of a matrix
    
    # FUNCTION:
    
    # Rank:
    method = method[1]
    if (method == "chol") {
        ans = attr(chol(x, pivot = TRUE), "rank") 
    } else {
        ans = qr(x)$rank 
    }
    
    # Return Value:
    ans 
}
        

# ------------------------------------------------------------------------------

    
tr = 
function(x) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns the trace of a matrix
    
    # FUNCTION:
    
    # Trace:
    if (dim(x)[1] != dim(x)[2] ) {
        return(NA) 
    } else {
        return(sum(diag(x))) 
    } 
        
    # Return Value:
    invisible()
}          


# ------------------------------------------------------------------------------


kron = 
function(x, y) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns Kronecker product
    
    # FUNCTION:
    
    # Kronecker Product:
    ans = x %*% y 
    
    # Return Value:
    ans
}


# ------------------------------------------------------------------------------


mexp =
function(x, order = 8, method = c("pade", "taylor"))
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Returns matrix exponential of a square matrix
    
    # Author:
    #   Package: mexp
    #   Version: 0.1
    #   Title: Matrix exponential
    #   Date: 2004-01-22
    #   Author: David Firth
    #   Maintainer: David Firth <d.firth@warwick.ac.uk>
    #   Description: Exponentiate a matrix by Pade or Taylor approximation
    #   License: GPL Version 2 or later

    # FUNCTION:
    
    # Checks:
    method = method[1]
    a = x 
    if (!is.matrix(a)) 
        stop("invalid (non-matrix) argument")
    if (dim(a)[1] != dim(a)[2]) 
        stop("matrix not square")
    if (!is.numeric(order)) 
        stop("order must be an integer number")
    if (!(method %in% c("pade", "taylor"))){
        stop("method must be \"pade\" or \"taylor\"")} 
            
    # Compute:
    size = as.integer(dim(a)[1])
    a = as.double(as.vector(a))
    order = as.integer(order)
    ntaylor = npade = 0
    if (method == "Pade") {
        npade = order 
    } else {
        ntaylor = order
    }
    accuracy = as.double(0)
    result = .Fortran("matrexp", 
        a, 
        size, 
        ntaylor, 
        npade, 
        accuracy,
        PACKAGE = "fMultivar")
    accuracy = result[[5]]
    result = matrix(result[[1]], size, size)
    attr(result, "accuracy") = accuracy
    attr(result, "method") = method
    attr(result, "order") = order
    
    # Return Value:
    result
}


# ------------------------------------------------------------------------------


vec = 
function(x)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   vec is the operator that stacks a matrix
    #   as a column vector:
    #   vec(X) = (X11, X21, ..., XN1, X12, X22, ..., XNN)'

    # Note:
    #   Example for a 3x3 Matrix:
    #   X11, X21, X22, X31, X32, X33
    
    # FUNCTION:
    
    # Return Value:
    t(t(as.vector(x)))
}


# ------------------------------------------------------------------------------

vech = 
function(x)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   vech is the operator that stacks the lower triangle
    #   of a NxN matrix as an N(N+1)/2x1 vector:
    #   vech(X) =(X11, X21, X22, X31, ..., XNN)'
    
    # Note:
    #   Example for a 3x3 Matrix:
    #   X11, X21, X22, X31, X32, X33
    
    # FUNCTION:
    
    # Return Value:
    t(x[!upper.tri(x)])
}


################################################################################
#  chol                 R  returns the Cholesky factor matrix
#  eigen                R  returns eigenvalues and eigenvectors
#  svd                  R  returns the singular value decomposition
#  kappa                R  returns the condition number of a matrix
#  qr                   R  returns the QR decomposition of a matrix
#  solve                R  solves a system of linear equations
#  backsolve            R  ... use when the matrix is upper triangular
#  forwardsolve         R  ... use when the matrix is lower triangular


################################################################################
#  tslag                R  Lagged or leading vector/matrix of selected order(s)
#  .tslag1                 Internal Function used by tslag
#  pdl                  R  Regressor matrix for polynomial distributed lags


.tslag1 = 
function(x, k) 
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Internal Function used by function tslag.
          
    # FUNCTION:
    y = x
    if (k > 0) y = c(rep(NA, times = k), x[1:(length(x)-k)])
    if (k < 0) y = c(x[(-k+1):length(x)], rep(NA, times = -k))
    
    # Return Value:
    y 
}


# ------------------------------------------------------------------------------


tslag = 
function(x, k = 1, trim = FALSE)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Creates a lagged or leading vector/matrix of selected order(s).
    
    # Arguments:
    #   x - a vector of data, missing values (NA) are allowed. 
    #   k - the number of positions the new series is to lag 
    #       or to lead the input series. 
    #   trim - a logical flag, if TRUE, the missing values at the 
    #       beginning or end of the returned series will be trimmed. 
    #       The default value is FALSE. 
    
    # Details:
    #   With a positive value of "k" we get a lagged series and with
    #   a negative value we get a leading series. 
    
    # Examples:
    #   tslag(rnorm(10), 2)
    #   tslag(rnorm(10), -2:2)
    #   tslag(rnorm(10), -2:2, trim = TRUE)
    
    # FUNCTION:
        
    # Bind:
    ans = NULL
    for ( i in k) {
        ans = cbind(ans, .tslag1(x, i)) 
    }
        
    # Trim:
    if (trim) {
        indexes = (1:length(ans[,1]))[!is.na(apply(ans, 1, sum))]
        ans = ans[indexes, ] 
    }
        
    # As Vector:
    if (length(k) == 1) ans = as.vector(ans)
    
    # Return Value:
    ans
}


# ------------------------------------------------------------------------------


pdl = 
function(x, d = 2, q = 3, trim = FALSE)
{   # A function implemented by Diethelm Wuertz

    # Description:
    #   Regressor matrix for polynomial distributed lags
    
    # Aruments:
    #   x - a numeric vector.
    #   d - an integer specifying the order of the polynomial. 
    #   q - an integer specifying the number of lags to use in 
    #       creating polynomial distributed lags. This must be 
    #       greater than d. 
    #   trim - a logical flag; if TRUE, the missing values at 
    #       the beginning of the returned matrix will be trimmed. 

    # Value:
    #   Returns a matrix representing the regressor matrix. 

    # Example:
    #   stack.loss = c(
    #       42, 37, 37, 28, 18, 18, 19, 20, 15, 14, 14, 
    #       13, 11, 12,  8,  7,  8,  8,  9, 15, 15)
    #   pdl(stack.loss)
    
    # FUNCTION:
    
    # Check:
    stopifnot(q > d)

    # Polynomial distributed lags:
    M = tslag(x, 1:q, FALSE)
    C = NULL
    for (i in 0:d) { C = rbind(C, (1:q)^i) }
    Z = NULL
    for (i in 1:(d+1)) { Z = cbind(Z, apply(t(C[i,]*t(M)), 1, sum)) }
    Z[, 1] = Z[, 1] + x
    
    # Trim:
    if (trim) {
        indexes = (1:length(Z[,1]))[!is.na(apply(Z, 1, sum))]
        Z = Z[indexes, ] }

    # Return Value:
    Z
}


################################################################################