-
Notifications
You must be signed in to change notification settings - Fork 0
/
examples.R
5121 lines (3850 loc) · 134 KB
/
examples.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
## -*- coding: utf-8 -*-
## examples.R
## Author: René Locher
## Version: 2020-04-18
pathIn <- "data/"
options(width = 72) ## width of default emacs
options(max.print = 300) ## stops printing after 300 values
options(contrasts = c("contr.treatment", "contr.poly"))
## Show help in browser
options(help_type = "html")
onError <- function() {
graphics.off()
}
options(error = utils::recover)
## enter recover() on error. See further below
rm(list = objects()) ## deletes workspace, sparing all dot objects
rm(list = objects(all.names = TRUE)) ## deletes everything
options()
## Give environment variables back:
R.home() # R_HOME
R.home("bin")
R.home("doc")
R.home("etc")
Sys.getenv("R_HOME")
Sys.getenv("R_USER")
Sys.getenv("R_ENVIRON_USER")
warnings() ## print last warnings
warning() ## clear last warnings
## Show paths to libraries
.libPaths()
as.double() ## equivalent to as.real(), as.numeric()
## HTML-Hilfe in Browser starten
help.start()
help.search("regression")
help.search("regression", fields = "concept")
help.search("regression", fields = "keyword")
help.search("multivariate", fields = "keyword")
?"%%"
?Syntax
library(help = "base")
apropos("plot")
### see also http://stat.ethz.ch/CRAN/index.html / Search /
## .. / Search mail archives / google
## Tip: search for error message
## store objects out of functions into (new) environments
## linking an object to a function
?lockBinding
source("E:\\lor\\S\\goodies.R")
help.search.google('hexagon')
help.search.archive('memory')
vignette() ## Show vignettes of all packages installed
vignette(package = "grid")
vignette("displaylist", package = "grid")
browseVignettes(package = "grid")
citation("grid")
maintainer("grid")
packageVersion("grid")
packageDescription("grid")
read.table(file = "http://stat.ethz.ch/Teaching/Datasets/NDK/air.dat")
## Attention:
## numeric values are rounded to 7 digits before storing values
## you might change that behaviour by options(digits =
## random seeds
set.seed(1)
save.seed <- .Random.seed
set.seed(save.seed)
sample(1000, 1)
set.seed(save.seed)
sample(1000, 1)
## Testing and Compiling packages
## RD-section: \dontrun{}
## R CMD check gains options --run-dontrun and --run-donttest.
## R CMD build supports pandoc files: *.md
tools::testInstalledPackage()
## loading package from github
library(devtools)
install_github("Oliver4242/testdemo")
library(testdemo)
testfun()
## Basic data types ----------------------------------------
is(5L)
is(5)
as.octmode(10)
## Bitwise Logical Operations ----------------------------------------
bitwAnd(5L, 4L)
bitwAnd(8L, 4L)
bitwAnd(7L, 4L)
bitwAnd(19L, 17L)
## Measuring Run Time ----------------------------------------
fun <- function(n = 10000, fun = function(x) x) {
# Purpose: Test if system.time works; n: loop size
fun(for(i in 1:n) x <- mean(rt(1000, df = 4)))
}
system.time(fun(5000))
## user system elapsed
## 1.06 0.00 1.06
started <- Sys.time()
fun(5000)
difftime(Sys.time(), started, units = "sec")
microbenchmark::microbenchmark(fun(5000), times = 10)
##----------------------------------------
library(IDPmisc)
detach(package:IDPmisc)
search() ## search path of R
##----------------------------------------
save.image() # save binary data to harddisk
save(list = ls(all = TRUE), file = ".RData") # = save.image()
load("e:/lor/Charite/0312/.RData") # read binary data from disk
unload()
dump() # store ojects from ASCII file
source() # load ojects from ASCII file
data() # list all datasets included in R and attached libraries
?iris
head(iris) # show first 6 lines of dataset
tail(iris, n = 2)
example(head) # Beispiele einer Funktion aufrufen
promptData(sunspots)
prompt(sunspots)
remove(list = objects(pattern = "^t\\.")) # immer mit list-Argument
## alle Namen, welche mit "." Starten
objects(pattern = "^\\.", all.names = TRUE)
## alle ohne Namen, welche mit "." Starten
objects(pattern = "^[^\\.]", all.names = TRUE)
## Umlaute
print("äöü")
## geht nicht (mehr?) korrekt in emacs!!
plot(rnorm(100), main = "äöü")
## redirecting output
sink(file = "test.txt")
1:10
cat("\n\n")
"done"
sink(file = NULL)
##----------------------------------------
## system near functions
## shows the actual capabilities of R, e.g. graphic drivers, tcltk, ...
capabilities()
## Accuracy of R
str(.Machine)
## run this for error reports
sessionInfo()
.Platform
win.version()
version
contributors()
setwd("e:/lor/R/") #setting working directory
getwd() #getting working directory
?environment
browseEnv()
environment()
globalenv()
.BaseNamespaceEnv
Sys.getenv("PROCESSOR_IDENTIFIER")
## reading Windows path
Sys.getenv("PATH")
system(command = "CMD.EXE /C PATH", intern = TRUE) ## Alternative
## setting Windows path
Sys.setenv(PATH = "C:\\Windows\\system32;C:\\Windows")
Sys.getenv("HOMEPATH")
Sys.getenv("sysname")
## get version of installed java
system("java -version")
## Getting system time and date
date()
str(date())
Sys.time()
str(Sys.time())
## typing time
system(command = "CMD.EXE /C time /t", intern = TRUE) ## Alternative
Sys.getlocale()
## Settings for aprpriate Umlaute in R
## "LC_COLLATE = German_Switzerland.1252;LC_CTYPE = German_Switzerland.1252;LC_MONETARY = German_Switzerland.1252;LC_NUMERIC = C;LC_TIME = German_Switzerland.1252"
## (custom-set-variables '(current-language-environment "UTF-8"))
Sys.info()
Sys.info()["sysname"]
sys.status()
Sys.sleep(1)
.Platform
xx <- c("ex", "col", "old")
list.files(pattern = paste("(", paste(xx, collapse = ".*R$)|("), ".*R$)", sep = ""))
file.exists()
file.path()
file.show()
fileList <- file.info(list.files("E:/ZHAW", recursive = TRUE))
str(fileList)
range(fileList$size, na.rm = TRUE)
head(fileList)
system.file()
system.file(package = "stats") # The root of package 'stats'
R.home()
Sys.setlocale()
Sys.getlocale()
Sys.localeconv()
?Encoding
iconvlist()
localeToCharset()
## uses system facilities to convert a character vector between encodings: the 'i' stands for 'internationalization'
enc2utf8("Ü")
x <- "fa\xE7ile"
Encoding(x)
x
enc2utf8(x)
xx <- iconv(x, "latin1", "UTF-8")
Encoding(c(x, xx))
c(x, xx)
Encoding(xx) <- "bytes"
xx # will be encoded in hex
cat("xx = ", xx, "\n", sep = "")
iconv(x, "latin1", "ISO8859-1")
## convenient configurations for R on windows
## location for private files of Rconsole etc (see ?Rconsole):
## set R_USER E:\lor\R\profile
## set R_PROFILE E:\lor\R\profile\start.R
## see also CRAN -> an introduction to R ->
## invoking R from the command line
##configuration of console and the pager in
## ..\etc\Rconsole
?Rconsole
?Rprofile
## starting R in single windows:
## C:\Programme\R\bin\Rgui.exe --sdi
## DOS> rterm < inpFile #Old Version of Batch-Prozess
## Windows> rscript < inpFile
## encoding stdin
rterm --encoding
## CP1252 = latin1 superset
shell("dir")
shell("cd")
## works only in R-GUI
shell("cmd /k cd %userprofile%", intern = TRUE)
object.size
##----------------------------------------
## namespace and classes
library(tkrplot) # viewing databases, class hierarchies
## show hidden objects
MASS:::rlm.default
## S3-Classes
methods(print)
## the next two examples return identical results:
## getS3method() findet aber auch Methoden, welche im namespace versteckt sind
getS3method("aggregate", "data.frame")
aggregate.data.frame
getS3method("plot", "default") ## search for S3 object
getAnywhere(plot) ## search for S4 object
getFromNamespace("plot", "graphics")
library(IDPmisc)
getAnywhere(plot)
getAnywhere(plot)[1]
methods(plot) ## print all S3 functions
showMethods(plot) ## print all S4 functions
## Function: plot (package graphics)
## x = "ANY", y = "ANY" ## S3 plot functions
## x = "rose", y = "missing" ## new function from IDPmisc
library(R.methodsS3)
?R.methodsS3
R.KEYWORDS
?S3
## S4
library(help = methods)
## library(methods) ## is called by default
?S4
?dotsMethods
selectMethod("plot", "rose")
selectMethod("plot", "ANY")
## plot S4 methods to all existing signatures
findMethods("plot")
findMethods("plot")@names
getMethod("plot", c("rose", "ANY"))
## No method found for function "plot" and signature rose
## -> S4 class!!
## plot method for default method
getMethod("plot", c("ANY", "ANY"))
showClass("rose")
methods ? show
showClass("rose")
MethodsList("rose")
MethodsList("plot")
MethodsList("function")
isGeneric("rose")
isGeneric("plot")
## another example for analysing method-4-functions
library(Biostrings)
showMethods(needwunsQS)
getMethod("needwunsQS", c("BString", "character"))
getMethod("needwunsQS", c("character", "BString"))
getMethod("needwunsQS", c("character", "character"))
Biostrings:::.needwunsQS
##----------------------------------------
## new classes
## be careful: don't use argument "names" in representation()!!
val.dat.dir <- function(x)
{
if (length(x@dir)! = nrow(x@x))
return("nrow(x) must be equal to length(dir)")
if (sum(is.na(x@dir)) > 0)
stop("slot 'dir' must not contain NAs!") else return(TRUE)
}
setClass("dat.dir",
representation(x = "matrix", dir = "numeric"),
validity = val.dat.dir)
getClass("dat.dir")
tt <- new("dat.dir",
x = matrix(1:4, nrow = 2, dimnames = list(1:2, 1:2)),
dir = 10:11)
class(tt)
## analysing objects
data(ToothGrowth)
str(ToothGrowth)
class(ToothGrowth) # "data.frame"
is(ToothGrowth) # "data.frame" "oldClass"
mode(ToothGrowth) # "list"
sum(c(NA, NA), na.rm = TRUE) # 0!!
help.start() # Starte HTML-Hilfe
library(help = chron) # Liste der Funktionen in der Bibliothek chron
## packages
.packages(all.available = TRUE) # List all available packages
write.table(.packages(all.available = TRUE), file = "packages.txt")
.Defunct()
Deprecated()
write.matrix()
##
is.element(c(4:5, 11), 0:10)
x <- c(4:5, 11)
is.element(x, 0:10)
match(c(4:5, 11), 0:10)
isTRUE(0)
isTRUE(1)
isFALSE(0)
## scope of objects, lexical scoping ----------------------------------------
## Gültigkeitsbereich
xx <- 10
tf0 <- function(xx)
{xx <- xx + 1}
tf0(xx)
xx
tf1 <- function(xx)
{xx <<- xx + 1}
tf1(xx)
xx
tf2 <- function(yy)
{yy.nam <- deparse(substitute(yy))
## deparse must be called before first evaluation of yy!
yy <- yy + 1 ## 12
print(paste(yy.nam, yy, sep = ": "))
assign(yy.nam, yy + 1, env = .GlobalEnv) ## assign 13 to xx
}
xx
tf2(xx)
xx
## Execute a function call
## deparsing does not work as expected within a do.call because
## xx is already evaluated by do.call!!
do.call("tf2", list(xx))
xx
## To circumvent the execution
do.call("tf2", list(quote(xx)))
expression(pi)
eval(expression(pi))
parse(text = "pi") ## = expression(pi)
eval(parse(text = "pi"))
tf3 <-
function(arg) {
x <- deparse(substitute(arg))
print(x)
}
tf3(f)
tf3(arg = c(a, b, c))
## Demonstration of lazy evaluation ----------------------------------------
f1 <- function(x, y = x) { x <- x + 1; return(y)}
f2 <- function(x, y = eval(x)) { x <- x + 1; return(y) }
f4 <- function(x, y = x) { y <- y - 1; x <- x + 1; return(y) }
a <- 10
f1(a) # 11
f1(10) # 11
f1(a, 1) # 1
f2(a) # 11
f4(a) # 9
## Demonstration of substitution ----------------------------------------
s1 <-
function(x, y = substitute(x)) {
x <- x + 1
return(y)
}
s2 <-
function(x, y) {
if(missing(y)) y <- substitute(x)
x <- x + 1; return(y)
}
s3 <-
function(x, y = substitute(x)) {
x <- x + 1
y <- y - 1; return(y)
}
s4 <-
function(x, y = substitute(x)) {
y <- y - 1
x <- x + 1; return(y)
}
a # 10
s1(a) # 11
s2(a) # a
s3(a) # 10
s4(a) # Error in y - 1 : non-numeric argument to binary operator
eval(s2(a)) # 10
eval(s2(10)) # 10
typeof(s2(a)) # "symbol"
## manipulation of functions
names(formals(lm))
args(lm)
gdata::Args(lm)
## Function as an argument
f6 <- function(dev){
devNam <- deparse(substitute(dev))
if (devNam ! = "windows") {
dev(file = paste0("test.", devNam))
}
plot(rnorm(100))
if (devNam ! = "windows") dev.off()
} ## f6
f6(windows)
f6(pdf)
f6()
## demonstration for match.arg
f7 <- function(dev = c(c("windows", "pdf", "png"))){
dev <- match.arg(dev)
print(dev)
}
f7()
f7("pdf")
f7("a2")
f7(a2)
## demonstration for match.arg (2), functions as argument
f8 <- function(dev = c(c("windows", "pdf", "png"))){
ext <- match.arg(dev)
dev <- get(x = ext)
if (ext ! = "windows") {
dev(file = paste0("test.", ext))
}
plot(rnorm(100))
if (ext ! = "windows") dev.off()
}
f8()
f8("pdf")
## demonstration for ...
f9 <- function(a = c("a1", "a2"), ...){
a <- match.arg(a)
print(a)
if (length(list(...))) {
cat("\n...-args:\n")
print(list(...))
} else {
cat("\nno ...-args\n")
}
}
f9()
f9(a = "a1", "nothing")
f9(a = "a2", b = "xy")
f9(a = 5, b = "xy")
f10 <- function(...){
args <- list(...)
print(args)
}
f10()
f10(x1 = 15, x2 = 20:26, 1000)
f11 <- function(x){
cat("missing(x): ", missing(x), "\n")
cat("exists(x): ", exists(x), "\n")
cat("is.null(x): ", is.null(x), "\n")
cat("is.na(x)", is.na(x), "\n")
cat(missing(eval(substitute(x))))
}
f11()
f11("bla")
f11(bla)
x <- "bla"
f11(x)
f11(x = x)
f12 <- function(fun, ...)
{
fun(...)
}
f12(mean, 1:10)
f12(plot, 1:10, rnorm(10))
f13 <- function(fun, ...)
{
do.call(fun, list(...))
}
f13(mean, 1:10)
f13(mean, c(1:10, NA))
f13(mean, c(1:10, NA), na.rm = TRUE)
f13(plot, 1:10, rnorm(10))
f13(plot, 1:10, quote(rnorm(10)))
## changing single arguments in a ... list
library(lattice)
diag.f <- function(...) {
par.list <- list(...)
par.list$draw <- FALSE
do.call(diag.panel.splom, par.list)
}
splom(~iris, diag.panel = diag.f)
test <- function(x) {
print(exists(x))
if (!exists(x, inherits = FALSE))
print("x existiert nicht") else print(x)
}
test()
## sunflowerplot
sunflowerplot(x = sort(2*round(rnorm(100))), y = round(rnorm(100), 0),
main = "Sunflower Plot of Rounded N(0, 1)")
sunflowerplot(x = sort(2*round(rnorm(100))), y = round(rnorm(100), 0),
ann = FALSE, axes = FALSE, pch = 1)
box()
title(main = "Sunflower Plot of Rounded N(0, 1)",
xlab = "x", ylab = "y")
axis(1)
axis(2, at = 1, labels = "ja", las = 1)
## bquote for partial substitution
y <- paste(letters[1:4], "x", sep = ".")
bquote(y = = .(y))
a <- 2
bquote(a = = a)
quote(a = = a)
bquote(a = = .(a))
substitute(a = = A, list(A = a))
## comparisons
x <- 0.1 * (5:0)
x = = 0.3
x = = 0.5
##
x[3] = = 0.3
identical(x[3], 0.3)
all.equal(x[3], 0.3)
all.equal(x[3], 0.3, tol = 0)
x <- c(1, NA, 3)
x = = 1
identical(x, 1)
x <- c(2, 4, NA, 6, NA, 4)
duplicated(x)
unique(x)
ifelse(x > 4, "yes", "no")
unique(data.frame(A = c(1:3, 3), B = c(1:3, 3)))
##################################################################
## Memory problems
## garbage collection: räumt Memory auf
gc()
## Ncells: fixer Variablenraum in MB
## Vcells: dynamischer Variablenraum in MB (heap)
## per default sind keine maximalen Limiten angegeben
## R can adress a maximum of 4 GB RAM with 32-Bit-Processor
## On XP you can address only 2GB, on XP /3GB 3 GB
## -> http://cran.r-project.org/bin/windows/base/rw-FAQ.html, kap 2.9
## maximum amount of memory in MB obtained from the OS is reported
memory.size(max = TRUE)/1048576
## amount of memory in use
memory.size(max = FALSE)/1048576
## returns memory limit in MB
memory.limit(size = NA)
## XP32 default: 1535 in R-Gui
## sets memory limit in MB
## default: 1 GB
memory.limit(size = 1700)
## setting memory limits during startup:
c:\programme\R\bin\Rgui --max-mem-size = 1700M
## 1 double = 8 Byte
##----------------------------------------
## debugging
browser() ## set test point in code
c ## exit browser and continue execution at next statement
n ## next statement, stepping over function calls
s ## next statement, stepping into function calls
f ## finish function of current loop
Q ## quit browser mode
## Debugging for S3- and S4-methods
?debug
?debugonce
?undebug
?isdebugged
options(error = recover)
## When called, recover prints the list of current calls, and prompts the user to select one of them. The standard R browser is then invoked from the corresponding environment; the user can type ordinary R language expressions to be evaluated in that environment.
## When finished browsing in this call, type c to return to recover from the browser. Type another frame number to browse some more, or type 0 to exit recover.
?bug.report
sessionInfo()
## it shows always the line before executing it
f <- function(x, y){
if(missing(y)) y <- x^3
M <- x^2
return(y-x)
}
debug(f)
f(3, 2)
undebug(f)
trace("f", browser, exit = browser)
f(3)
untrace(f)
## Debug function when non fatal error occurs
fErr <- function(x){
optionsOld <- options()
options(error = browser())
lm(x)
options(optionsOld)
}
fErr(3)
options()$error
## this is a really comfortable debugging mode:
library(debug)
mtrace(f)
mtrace(f, FALSE)
## main commands in debugging window:
## go(5) ## go to line 5
## go() ## go on until error occurs
## br(10) ## set break to line 10
## skip(15) ## go to line 15 without executing any code
## More about debugging in R-Extensions.pdf, Debugging
## Profiling Code
Rprof("impute.txt")
impute()
Rprof(NULL)
summaryRprof
## Analyse it by > R CMD Rprof impute.txt
## More sophisticated tools in
library(proftools)
## See also R-Extensions.pdf, Tidying and profiling R code
options(error = recover) #
## After error, 'recover' prints the list of current calls, and
## prompts the user to select one of them.
traceback() # prints the call stack of the last uncaught error
##----------------------------------------
## error handling
g <- function(x){
xStr <- deparse(substitute(x))
if (xStr == "") {
stop("x is missing!\n")
} else {
if (inherits(try(is(x), silent = TRUE), "try-error")) {
stop(xStr, " is not defined\n")
}
}
cat("x: ", x, "\n")
}
g(1)
g()
g(notDefined)
x <- try(1/a, silent = TRUE)
x
inherits(x, "try-error")
## Print last error message
geterrmessage()
simpleError(x)
simpleWarning(x)
x <- 1:10
x[3] <- try(1/a, silent = TRUE)
x
inherits(x, "try-error")
simpleError(x)
## More flexible with tryCatch()
errFun <-
function(e)
{
cat("errFun:", geterrmessage(), "\n")
}
warnFun <-
function(e)
{
cat("warnFun:", conditionMessage(e), "\n")
}
finFun <-
function()
{
cat("Executed before leaving tryCatch\n")
}
tryCatch(log(a),
error = errFun,
warning = warnFun,
finally = finFun())
tryCatch(log(-1),
error = errFun,
warning = warnFun,
finally = finFun())
tryCatch(log(1),
error = errFun,
warning = warnFun,
finally = finFun())
## executes code defined in on.exit() when exiting current function (or R)
on.exit()
## prompt error message and exit function
stop("without reason")
## prompt warning
warning("bla")
##----------------------------------------
## Operators
a <- c(TRUE, TRUE, FALSE)
b <- c(TRUE, FALSE, FALSE)
a&b
a&&b
a&&rev(b)
#####################################################
## Plotting Devices
## Windows Meta Files
windows(width = 20, height = 20, pointsize = 10)
plot(rnorm(20))
savePlot(filename = "E:\\lor\\test", type = "wmf")
## Lossles compression: 10kB
## Empfohlenes Device für Punkt- und Liniengrafiken für Import nach Word
png(file = "10x10.png", width = 10, height = 10, unit = "cm", res = 300, pointsize = 10)
plot(rnorm(100), col = col)
dev.off()
## Komprimierung mit Qualität 75%: 34kB
jpeg(file = "10x10.jpg", width = 10, height = 10, unit = "cm", res = 300,
quality = 75, pointsize = 10)
plot(rnorm(100), col = col)
dev.off()
## Verlustfrei komprimiert und vektorbasiert abgespeichert: 6kB
## Empfohlenes Device für Latex
inch <- 2.54
pdf(file = "10x10.pdf", width = 10/inch, height = 10/inch, pointsize = 10)
plot(rnorm(100), col = col)
dev.off()
## für 26"-Bildschirm von Dell
xpinch <- 2560/60*inch
ypinch <- 1440/34*inch
windows(width = 10/inch, height = 10/inch, xpinch = xpinch, ypinch = ypinch)
## The bitmap() device does not support transparency.
bmp()
## not recommended
bitmap()
## Lossy. Useful for images
jpg()
postscript()
## Lossy. Useful for images and especially for series of images
## on one or more pages
## Arguments for landscape A4 plots
pdf(file = "test.pdf",
width = 26/2.54, height = 18/2.54,
paper = "a4r", pointsize = 12)
plot(rnorm(100))
dev.off()
## ----------------------------------------
x <- rnorm(100)
qqnorm(x)
qqline(x, col = "red")
#################################################################
## data manipulation
library(help = gdata)
library(help = IDPmisc)
##################################################################
library(nnet)
multinom()
library(help = Design)
## logistic regression, Cox regression, accelerated failure time models,
## ordinary linear models, the Buckley-James model,
## and generalized least squares for serially or spatially correlated observations.
library(Design)
validate.lrm() ## Resampling Validation of a Logistic Model
#################################################################