-
Notifications
You must be signed in to change notification settings - Fork 0
/
base-Ex.R
9726 lines (6888 loc) · 204 KB
/
base-Ex.R
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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pkgname <- "base"
source(file.path(R.home("share"), "R", "examples-header.R"))
options(warn = 1)
options(pager = "console")
assign(".oldSearch", search(), pos = 'CheckExEnv')
cleanEx()
nameEx("Arithmetic")
### * Arithmetic
flush(stderr()); flush(stdout())
### Name: Arithmetic
### Title: Arithmetic Operators
### Aliases: + - * ** / ^ %% %/% Arithmetic
### Keywords: arith
### ** Examples
x <- -1:12
x + 1
2 * x + 3
x %% 2 #-- is periodic
x %/% 5
cleanEx()
nameEx("Bessel")
### * Bessel
flush(stderr()); flush(stdout())
### Name: Bessel
### Title: Bessel Functions
### Aliases: bessel Bessel besselI besselJ besselK besselY
### Keywords: math
### ** Examples
require(graphics)
nus <- c(0:5, 10, 20)
x <- seq(0, 4, length.out = 501)
plot(x, x, ylim = c(0, 6), ylab = "", type = "n",
main = "Bessel Functions I_nu(x)")
for(nu in nus) lines(x, besselI(x, nu=nu), col = nu+2)
legend(0, 6, legend = paste("nu=", nus), col = nus+2, lwd = 1)
x <- seq(0, 40, length.out = 801); yl <- c(-.8, .8)
plot(x, x, ylim = yl, ylab = "", type = "n",
main = "Bessel Functions J_nu(x)")
for(nu in nus) lines(x, besselJ(x, nu=nu), col = nu+2)
legend(32,-.18, legend = paste("nu=", nus), col = nus+2, lwd = 1)
## Negative nu's :
xx <- 2:7
nu <- seq(-10, 9, length.out = 2001)
op <- par(lab = c(16, 5, 7))
matplot(nu, t(outer(xx, nu, besselI)), type = "l", ylim = c(-50, 200),
main = expression(paste("Bessel ", I[nu](x), " for fixed ", x,
", as ", f(nu))),
xlab = expression(nu))
abline(v=0, col = "light gray", lty = 3)
legend(5, 200, legend = paste("x=", xx), col=seq(xx), lty=seq(xx))
par(op)
x0 <- 2^(-20:10)
plot(x0, x0^-8, log="xy", ylab="",type="n",
main = "Bessel Functions J_nu(x) near 0\n log - log scale")
for(nu in sort(c(nus, nus+.5)))
lines(x0, besselJ(x0, nu=nu), col = nu+2)
legend(3, 1e50, legend = paste("nu=", paste(nus, nus+.5, sep=",")),
col = nus + 2, lwd = 1)
plot(x0, x0^-8, log="xy", ylab="", type="n",
main = "Bessel Functions K_nu(x) near 0\n log - log scale")
for(nu in sort(c(nus, nus+.5)))
lines(x0, besselK(x0, nu=nu), col = nu+2)
legend(3, 1e50, legend = paste("nu=", paste(nus, nus+.5, sep=",")),
col = nus + 2, lwd = 1)
x <- x[x > 0]
plot(x, x, ylim=c(1e-18, 1e11), log = "y", ylab = "", type = "n",
main = "Bessel Functions K_nu(x)")
for(nu in nus) lines(x, besselK(x, nu=nu), col = nu+2)
legend(0, 1e-5, legend=paste("nu=", nus), col = nus+2, lwd = 1)
yl <- c(-1.6, .6)
plot(x, x, ylim = yl, ylab = "", type = "n",
main = "Bessel Functions Y_nu(x)")
for(nu in nus){
xx <- x[x > .6*nu]
lines(xx, besselY(xx, nu=nu), col = nu+2)
}
legend(25, -.5, legend = paste("nu=", nus), col = nus+2, lwd = 1)
## negative nu in bessel_Y -- was bogus for a long time
curve(besselY(x, -0.1), 0, 10, ylim = c(-3,1), ylab = '')
for(nu in c(seq(-0.2, -2, by = -0.1)))
curve(besselY(x, nu), add = TRUE)
title(expression(besselY(x, nu) * " " *
{nu == list(-0.1, -0.2, ..., -2)}))
graphics::par(get("par.postscript", pos = 'CheckExEnv'))
cleanEx()
nameEx("Colon")
### * Colon
flush(stderr()); flush(stdout())
### Name: Colon
### Title: Colon Operator
### Aliases: : colon
### Keywords: manip
### ** Examples
1:4
pi:6 # real
6:pi # integer
f1 <- gl(2,3); f1
f2 <- gl(3,2); f2
f1:f2 # a factor, the "cross" f1 x f2
cleanEx()
nameEx("Comparison")
### * Comparison
flush(stderr()); flush(stdout())
### Name: Comparison
### Title: Relational Operators
### Aliases: < <= == != >= > Comparison collation
### Keywords: logic
### ** Examples
x <- stats::rnorm(20)
x < 1
x[x > 0]
x1 <- 0.5 - 0.3
x2 <- 0.3 - 0.1
x1 == x2 # FALSE on most machines
identical(all.equal(x1, x2), TRUE) # TRUE everywhere
cleanEx()
nameEx("Constants")
### * Constants
flush(stderr()); flush(stdout())
### Name: Constants
### Title: Built-in Constants
### Aliases: LETTERS letters month.abb month.name pi
### Keywords: sysdata
### ** Examples
## John Machin (ca 1706) computed pi to over 100 decimal places
## using the Taylor series expansion of the second term of
pi - 4*(4*atan(1/5) - atan(1/239))
## months in English
month.name
## months in your current locale
format(ISOdate(2000, 1:12, 1), "%B")
format(ISOdate(2000, 1:12, 1), "%b")
cleanEx()
nameEx("Control")
### * Control
flush(stderr()); flush(stdout())
### Name: Control
### Title: Control Flow
### Aliases: Control if else for in while repeat break next
### Keywords: programming iteration logic
### ** Examples
for(i in 1:5) print(1:i)
for(n in c(2,5,10,20,50)) {
x <- stats::rnorm(n)
cat(n,":", sum(x^2),"\n")
}
f = factor(sample(letters[1:5], 10, replace=TRUE))
for( i in unique(f) ) print(i)
cleanEx()
nameEx("Cstack_info")
### * Cstack_info
flush(stderr()); flush(stdout())
### Name: Cstack_info
### Title: Report Information on C Stack Size and Usage
### Aliases: Cstack_info
### Keywords: utilities
### ** Examples
Cstack_info()
cleanEx()
nameEx("DateTimeClasses")
### * DateTimeClasses
flush(stderr()); flush(stdout())
### Name: DateTimeClasses
### Title: Date-Time Classes
### Aliases: DateTimeClasses POSIXct POSIXlt POSIXt print.POSIXct
### print.POSIXlt summary.POSIXct summary.POSIXlt +.POSIXt -.POSIXt
### Ops.POSIXt Math.POSIXt Summary.POSIXct Math.POSIXlt Summary.POSIXlt
### [.POSIXct [<-.POSIXct [[.POSIXct [.POSIXlt [<-.POSIXlt
### as.data.frame.POSIXct as.data.frame.POSIXlt as.list.POSIXct
### .leap.seconds is.na.POSIXlt all.equal.POSIXct c.POSIXct c.POSIXlt
### as.matrix.POSIXlt length.POSIXlt mean.POSIXct mean.POSIXlt str.POSIXt
### check_tzones duplicated.POSIXlt unique.POSIXlt split.POSIXct
### date-time
### Keywords: utilities chron
### ** Examples
cleanEx()
nameEx("Dates")
### * Dates
flush(stderr()); flush(stdout())
### Name: Dates
### Title: Date Class
### Aliases: Date Dates print.Date summary.Date Math.Date Summary.Date
### [.Date [<-.Date [[.Date as.data.frame.Date as.list.Date c.Date
### mean.Date split.Date
### Keywords: utilities chron
### ** Examples
## Not run:
##D (today <- Sys.Date())
##D format(today, "%d %b %Y") # with month as a word
##D (tenweeks <- seq(today, length.out=10, by="1 week")) # next ten weeks
##D weekdays(today)
##D months(tenweeks)
##D as.Date(.leap.seconds)
## End(Not run)
cleanEx()
nameEx("Encoding")
### * Encoding
flush(stderr()); flush(stdout())
### Name: Encoding
### Title: Read or Set the Declared Encodings for a Character Vector
### Aliases: Encoding Encoding<- enc2native enc2utf8
### Keywords: utilities character
### ** Examples
## x is intended to be in latin1
x <- "fa\xE7ile"
Encoding(x)
Encoding(x) <- "latin1"
x
xx <- iconv(x, "latin1", "UTF-8")
Encoding(c(x, xx))
c(x, xx)
cleanEx()
nameEx("Extract")
### * Extract
flush(stderr()); flush(stdout())
### Name: Extract
### Title: Extract or Replace Parts of an Object
### Aliases: Extract Subscript [ [.listof [.simple.list [[ $ [<- [[<- $<-
### Keywords: array list
### ** Examples
x <- 1:12
m <- matrix(1:6, nrow=2, dimnames=list(c("a", "b"), LETTERS[1:3]))
li <- list(pi=pi, e = exp(1))
x[10] # the tenth element of x
x <- x[-1] # delete the 1st element of x
m[1,] # the first row of matrix m
m[1, , drop = FALSE] # is a 1-row matrix
m[,c(TRUE,FALSE,TRUE)]# logical indexing
m[cbind(c(1,2,1),3:1)]# matrix numeric index
ci <- cbind(c("a", "b", "a"), c("A", "C", "B"))
m[ci] # matrix character index
m <- m[,-1] # delete the first column of m
li[[1]] # the first element of list li
y <- list(1,2,a=4,5)
y[c(3,4)] # a list containing elements 3 and 4 of y
y$a # the element of y named a
## non-integer indices are truncated:
(i <- 3.999999999) # "4" is printed
(1:5)[i] # 3
## named atomic vectors, compare "[" and "[[" :
nx <- c(Abc = 123, pi = pi)
nx[1] ; nx["pi"] # keeps names, whereas "[[" does not:
nx[[1]] ; nx[["pi"]]
## Don't show:
stopifnot(identical(names(nx[1]), "Abc"),
identical(names(nx["pi"]), "pi"),
is.null(names(nx[["Abc"]])), is.null(names(nx[[2]])))
## End Don't show
## recursive indexing into lists
z <- list( a=list( b=9, c='hello'), d=1:5)
unlist(z)
z[[c(1, 2)]]
z[[c(1, 2, 1)]] # both "hello"
z[[c("a", "b")]] <- "new"
unlist(z)
## check $ and [[ for environments
e1 <- new.env()
e1$a <- 10
e1[["a"]]
e1[["b"]] <- 20
e1$b
ls(e1)
cleanEx()
nameEx("Extract.data.frame")
### * Extract.data.frame
flush(stderr()); flush(stdout())
### Name: Extract.data.frame
### Title: Extract or Replace Parts of a Data Frame
### Aliases: [.data.frame [[.data.frame [<-.data.frame [[<-.data.frame
### $<-.data.frame
### Keywords: array
### ** Examples
sw <- swiss[1:5, 1:4] # select a manageable subset
sw[1:3] # select columns
sw[, 1:3] # same
sw[4:5, 1:3] # select rows and columns
sw[1] # a one-column data frame
sw[, 1, drop = FALSE] # the same
sw[, 1] # a (unnamed) vector
sw[[1]] # the same
sw[1,] # a one-row data frame
sw[1,, drop=TRUE] # a list
sw["C", ] # partially matches
sw[match("C", row.names(sw)), ] # no exact match
try(sw[, "Ferti"]) # column names must match exactly
## Don't show:
stopifnot(identical(sw[,1], sw[[1]]),
identical(sw[,1][1], 80.2),
identical(sw[,1, drop = FALSE], sw[1]),
is.data.frame(sw[1]), dim(sw[1] ) == c(5,1),
is.data.frame(sw[1,]),dim(sw[1,]) == c(1,4),
is.list(s1 <- sw[1,, drop=TRUE]), identical(s1$Fertility, 80.2))
## End Don't show
swiss[ c(1, 1:2), ] # duplicate row, unique row names are created
sw[sw <= 6] <- 6 # logical matrix indexing
sw
## adding a column
sw["new1"] <- LETTERS[1:5] # adds a character column
sw[["new2"]] <- letters[1:5] # ditto
sw[, "new3"] <- LETTERS[1:5] # ditto
sw$new4 <- 1:5
sapply(sw, class)
sw$new4 <- NULL # delete the column
sw
sw[6:8] <- list(letters[10:14], NULL, aa=1:5)
# update col. 6, delete 7, append
sw
## matrices in a data frame
A <- data.frame(x=1:3, y=I(matrix(4:6)), z=I(matrix(letters[1:9],3,3)))
A[1:3, "y"] # a matrix
A[1:3, "z"] # a matrix
A[, "y"] # a matrix
## keeping special attributes: use a class with a
## "as.data.frame" and "[" method:
as.data.frame.avector <- as.data.frame.vector
`[.avector` <- function(x,i,...) {
r <- NextMethod("[")
mostattributes(r) <- attributes(x)
r
}
d <- data.frame(i= 0:7, f= gl(2,4),
u= structure(11:18, unit = "kg", class="avector"))
str(d[2:4, -1]) # 'u' keeps its "unit"
## Don't show:
stopifnot(identical(d[2:4,-1][,"u"],
structure(12:14, unit = "kg", class = "avector")))
## End Don't show
cleanEx()
nameEx("Extract.factor")
### * Extract.factor
flush(stderr()); flush(stdout())
### Name: Extract.factor
### Title: Extract or Replace Parts of a Factor
### Aliases: [.factor [<-.factor [[.factor [[<-.factor
### Keywords: category
### ** Examples
## following example(factor)
(ff <- factor(substring("statistics", 1:10, 1:10), levels=letters))
ff[, drop=TRUE]
factor(letters[7:10])[2:3, drop = TRUE]
cleanEx()
nameEx("Extremes")
### * Extremes
flush(stderr()); flush(stdout())
### Name: Extremes
### Title: Maxima and Minima
### Aliases: max min pmax pmin pmax.int pmin.int
### Keywords: univar arith
### ** Examples
require(stats); require(graphics)
min(5:1, pi) #-> one number
pmin(5:1, pi) #-> 5 numbers
x <- sort(rnorm(100)); cH <- 1.35
pmin(cH, quantile(x)) # no names
pmin(quantile(x), cH) # has names
plot(x, pmin(cH, pmax(-cH, x)), type='b', main= "Huber's function")
cleanEx()
nameEx("Last.value")
### * Last.value
flush(stderr()); flush(stdout())
### Name: Last.value
### Title: Value of Last Evaluated Expression
### Aliases: .Last.value
### Keywords: programming
### ** Examples
## These will not work correctly from example(),
## but they will in make check or if pasted in,
## as example() does not run them at the top level
gamma(1:15) # think of some intensive calculation...
fac14 <- .Last.value # keep them
library("splines") # returns invisibly
.Last.value # shows what library(.) above returned
## Don't show:
detach("package:splines")
## End Don't show
cleanEx()
nameEx("Log")
### * Log
flush(stderr()); flush(stdout())
### Name: log
### Title: Logarithms and Exponentials
### Aliases: log logb log10 log2 log1p exp expm1
### Keywords: math
### ** Examples
log(exp(3))
log10(1e7)# = 7
x <- 10^-(1+2*1:9)
cbind(x, log(1+x), log1p(x), exp(x)-1, expm1(x))
cleanEx()
nameEx("Logic")
### * Logic
flush(stderr()); flush(stdout())
### Name: Logic
### Title: Logical Operators
### Aliases: ! & && | || xor Logic isTRUE
### Keywords: logic
### ** Examples
y <- 1 + (x <- stats::rpois(50, lambda=1.5) / 4 - 1)
x[(x > 0) & (x < 1)] # all x values between 0 and 1
if (any(x == 0) || any(y == 0)) "zero encountered"
## construct truth tables :
x <- c(NA, FALSE, TRUE)
names(x) <- as.character(x)
outer(x, x, "&")## AND table
outer(x, x, "|")## OR table
cleanEx()
nameEx("MathFun")
### * MathFun
flush(stderr()); flush(stdout())
### Name: MathFun
### Title: Miscellaneous Mathematical Functions
### Aliases: abs sqrt
### Keywords: math
### ** Examples
require(stats) # for spline
require(graphics)
xx <- -9:9
plot(xx, sqrt(abs(xx)), col = "red")
lines(spline(xx, sqrt(abs(xx)), n=101), col = "pink")
cleanEx()
nameEx("Memory")
### * Memory
flush(stderr()); flush(stdout())
### Name: Memory
### Title: Memory Available for Data Storage
### Aliases: Memory mem.limits
### Keywords: environment
### ** Examples
# Start R with 10MB of heap memory and 500k cons cells, limit to
# 100Mb and 1M cells
## Not run:
##D ## Unix
##D R --min-vsize=10M --max-vsize=100M --min-nsize=500k --max-nsize=1M
## End(Not run)
cleanEx()
nameEx("NA")
### * NA
flush(stderr()); flush(stdout())
### Name: NA
### Title: Not Available / "Missing" Values
### Aliases: NA NA_integer_ NA_real_ NA_complex_ NA_character_ is.na
### is.na.data.frame is.na<- is.na<-.default
### Keywords: NA logic manip
### ** Examples
is.na(c(1, NA)) #> FALSE TRUE
is.na(paste(c(1, NA))) #> FALSE FALSE
(xx <- c(0:4))
is.na(xx) <- c(2, 4)
xx #> 0 NA 2 NA 4
cleanEx()
nameEx("NULL")
### * NULL
flush(stderr()); flush(stdout())
### Name: NULL
### Title: The Null Object
### Aliases: NULL as.null as.null.default is.null
### Keywords: attribute manip list sysdata
### ** Examples
is.null(list()) # FALSE (on purpose!)
is.null(integer(0))# F
is.null(logical(0))# F
as.null(list(a=1,b='c'))
cleanEx()
nameEx("NumericConstants")
### * NumericConstants
flush(stderr()); flush(stdout())
### Name: NumericConstants
### Title: Numeric Constants
### Aliases: NumericConstants 1L 0x1 1i
### Keywords: documentation
### ** Examples
2.1
typeof(2)
sqrt(1i) # remember elementary math?
utils::str(0xA0)
identical(1L, as.integer(1))
## You can combine the "0x" prefix with the "L" suffix :
identical(0xFL, as.integer(15))
cleanEx()
nameEx("Ops.Date")
### * Ops.Date
flush(stderr()); flush(stdout())
### Name: Ops.Date
### Title: Operators on the Date Class
### Aliases: +.Date -.Date Ops.Date
### Keywords: utilities chron
### ** Examples
cleanEx()
nameEx("Paren")
### * Paren
flush(stderr()); flush(stdout())
### Name: Paren
### Title: Parentheses and Braces
### Aliases: Paren ( {
### Keywords: programming
### ** Examples
f <- get("(")
e <- expression(3 + 2 * 4)
identical(f(e), e)
do <- get("{")
do(x <- 3, y <- 2*x-3, 6-x-y); x; y
## note the differences
(2+3)
{2+3; 4+5}
(invisible(2+3))
{invisible(2+3)}
cleanEx()
nameEx("Platform")
### * Platform
flush(stderr()); flush(stdout())
### Name: .Platform
### Title: Platform Specific Variables
### Aliases: .Platform
### Keywords: file utilities
### ** Examples
## Note: this can be done in a system-independent way
## by file.info()$isdir
if(.Platform$OS.type == "unix") {
system.test <- function(...) { system(paste("test", ...)) == 0 }
dir.exists <- function(dir)
sapply(dir, function(d)system.test("-d", d))
dir.exists(c(R.home(), "/tmp", "~", "/NO"))# > T T T F
}
cleanEx()
nameEx("Primitive")
### * Primitive
flush(stderr()); flush(stdout())
### Name: Primitive
### Title: Look Up a Primitive Function
### Aliases: .Primitive primitive
### Keywords: interface
### ** Examples
mysqrt <- .Primitive("sqrt")
c
.Internal # this one *must* be primitive!
`if` # need backticks
cleanEx()
nameEx("Random-user")
### * Random-user
flush(stderr()); flush(stdout())
### Name: Random.user
### Title: User-supplied Random Number Generation
### Aliases: Random.user
### Keywords: distribution sysdata
### ** Examples
## Not run:
##D ## Marsaglia's congruential PRNG
##D #include <R_ext/Random.h>
##D
##D static Int32 seed;
##D static double res;
##D static int nseed = 1;
##D
##D double * user_unif_rand()
##D {
##D seed = 69069 * seed + 1;
##D res = seed * 2.32830643653869e-10;
##D return &res;
##D }
##D
##D void user_unif_init(Int32 seed_in) { seed = seed_in; }
##D int * user_unif_nseed() { return &nseed; }
##D int * user_unif_seedloc() { return (int *) &seed; }
##D
##D /* ratio-of-uniforms for normal */
##D #include <math.h>
##D static double x;
##D
##D double * user_norm_rand()
##D {
##D double u, v, z;
##D do {
##D u = unif_rand();
##D v = 0.857764 * (2. * unif_rand() - 1);
##D x = v/u; z = 0.25 * x * x;
##D if (z < 1. - u) break;
##D if (z > 0.259/u + 0.35) continue;
##D } while (z > -log(u));
##D return &x;
##D }
##D
##D ## Use under Unix:
##D R CMD SHLIB urand.c
##D R
##D > dyn.load("urand.so")
##D > RNGkind("user")
##D > runif(10)
##D > .Random.seed
##D > RNGkind(, "user")
##D > rnorm(10)
##D > RNGkind()
##D [1] "user-supplied" "user-supplied"
## End(Not run)
cleanEx()
nameEx("Random")
### * Random
flush(stderr()); flush(stdout())
### Name: Random
### Title: Random Number Generation
### Aliases: Random RNG RNGkind RNGversion set.seed .Random.seed
### Keywords: distribution sysdata
### ** Examples
cleanEx()
nameEx("Recall")
### * Recall
flush(stderr()); flush(stdout())
### Name: Recall
### Title: Recursive Calling
### Aliases: Recall
### Keywords: programming
### ** Examples
## A trivial (but inefficient!) example:
fib <- function(n)
if(n<=2) { if(n>=0) 1 else 0 } else Recall(n-1) + Recall(n-2)
fibonacci <- fib; rm(fib)
## renaming wouldn't work without Recall
fibonacci(10) # 55
cleanEx()
nameEx("Round")
### * Round
flush(stderr()); flush(stdout())
### Name: Round
### Title: Rounding of Numbers
### Aliases: ceiling floor round signif trunc
### Keywords: arith
### ** Examples
round(.5 + -2:4) # IEEE rounding: -2 0 0 2 2 4 4
( x1 <- seq(-2, 4, by = .5) )
round(x1)#-- IEEE rounding !
x1[trunc(x1) != floor(x1)]
x1[round(x1) != floor(x1 + .5)]
(non.int <- ceiling(x1) != floor(x1))
x2 <- pi * 100^(-1:3)
round(x2, 3)
signif(x2, 3)
cleanEx()
nameEx("Special")
### * Special
flush(stderr()); flush(stdout())
### Name: Special
### Title: Special Functions of Mathematics
### Aliases: Special beta lbeta gamma lgamma psigamma digamma trigamma
### choose lchoose factorial lfactorial
### Keywords: math
### ** Examples
require(graphics)
choose(5, 2)
for (n in 0:10) print(choose(n, k = 0:n))
factorial(100)
lfactorial(10000)
## gamma has 1st order poles at 0, -1, -2, ...
## this will generate loss of precision warnings, so turn off
op <- options("warn")
options(warn = -1)
x <- sort(c(seq(-3,4, length.out=201), outer(0:-3, (-1:1)*1e-6, "+")))
plot(x, gamma(x), ylim=c(-20,20), col="red", type="l", lwd=2,
main=expression(Gamma(x)))
abline(h=0, v=-3:0, lty=3, col="midnightblue")
options(op)
x <- seq(.1, 4, length.out = 201); dx <- diff(x)[1]
par(mfrow = c(2, 3))
for (ch in c("", "l","di","tri","tetra","penta")) {
is.deriv <- nchar(ch) >= 2
nm <- paste(ch, "gamma", sep = "")
if (is.deriv) {
dy <- diff(y) / dx # finite difference
der <- which(ch == c("di","tri","tetra","penta")) - 1
nm2 <- paste("psigamma(*, deriv = ", der,")",sep='')
nm <- if(der >= 2) nm2 else paste(nm, nm2, sep = " ==\n")
y <- psigamma(x, deriv=der)
} else {
y <- get(nm)(x)
}
plot(x, y, type = "l", main = nm, col = "red")
abline(h = 0, col = "lightgray")
if (is.deriv) lines(x[-1], dy, col = "blue", lty = 2)
}
par(mfrow = c(1, 1))
## "Extended" Pascal triangle:
fN <- function(n) formatC(n, width=2)
for (n in -4:10) cat(fN(n),":", fN(choose(n, k= -2:max(3,n+2))), "\n")
## R code version of choose() [simplistic; warning for k < 0]:
mychoose <- function(r,k)
ifelse(k <= 0, (k==0),
sapply(k, function(k) prod(r:(r-k+1))) / factorial(k))
k <- -1:6
cbind(k=k, choose(1/2, k), mychoose(1/2, k))
## Binomial theorem for n=1/2 ;
## sqrt(1+x) = (1+x)^(1/2) = sum_{k=0}^Inf choose(1/2, k) * x^k :
k <- 0:10 # 10 is sufficient for ~ 9 digit precision:
sqrt(1.25)
sum(choose(1/2, k)* .25^k)
## Don't show:
k. <- 1:9
stopifnot(all.equal( (choose(1/2, k.) -> ck.),
mychoose(1/2, k.)),
all.equal(lchoose(1/2, k.), log(abs(ck.))),
all.equal(sqrt(1.25),
sum(choose(1/2, k)* .25^k)))
## End Don't show
graphics::par(get("par.postscript", pos = 'CheckExEnv'))
cleanEx()
nameEx("Startup")
### * Startup
flush(stderr()); flush(stdout())
### Name: Startup
### Title: Initialization at Start of an R Session
### Aliases: Startup Rprofile .Rprofile Rprofile.site Renviron
### Renviron.site .Renviron .First .First.sys .OptRequireMethods
### R_DEFAULT_PACKAGES R_ENVIRON R_ENVIRON_USER R_PROFILE R_PROFILE_USER
### Keywords: environment
### ** Examples
## Not run:
##D ## Example ~/.Renviron on Unix
##D R_LIBS=~/R/library
##D PAGER=/usr/local/bin/less
##D
##D ## Example .Renviron on Windows
##D R_LIBS=C:/R/library
##D MY_TCLTK="c:/Program Files/Tcl/bin"
##D
##D ## Example of setting R_DEFAULT_PACKAGES (from R CMD check)
##D R_DEFAULT_PACKAGES='utils,grDevices,graphics,stats'
##D # this loads the packages in the order given, so they appear on
##D # the search path in reverse order.
##D
##D ## Example of .Rprofile
##D options(width=65, digits=5)
##D options(show.signif.stars=FALSE)
##D setHook(packageEvent("grDevices", "onLoad"),
##D function(...) grDevices::ps.options(horizontal=FALSE))
##D set.seed(1234)
##D .First <- function() cat("\n Welcome to R!\n\n")
##D .Last <- function() cat("\n Goodbye!\n\n")
##D
##D ## Example of Rprofile.site
##D local({
##D # add MASS to the default packages, set a CRAN mirror
##D old <- getOption("defaultPackages"); r <- getOption("repos")
##D r["CRAN"] <- "http://my.local.cran"
##D options(defaultPackages = c(old, "MASS"), repos = r)
##D ## (for Unix terminal users) set the width from COLUMNS if set
##D cols <- Sys.getenv("COLUMNS")
##D if(nzchar(cols)) options(width = as.integer(cols))
##D })
##D