-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathqqBaseX-package.R
3171 lines (3013 loc) · 156 KB
/
qqBaseX-package.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
library(roxygen2);library(devtools)
package.name="qqBaseX";
remove.packages(package.name);
g=getwd();
dir.create("MyPackages");
setwd("MyPackages")
if(F){
remove.packages("qqBaseX");
devtools::install_github("AndreasFischer1985/qqBaseX")
}
create=function(
name="qqBaseX",
description=list("Package"="qqBaseX","Title"="Basic functions for analyzing qualitative and quantitative data based on R's default packages.","Version"="0.1.4","Authors@R"="person(\"Andreas\", \"Fischer\", email = \"andreasfischer1985@web.de\", role = c(\"aut\", \"cre\"))","Maintainer"="'Andreas Fischer' <andreasfischer1985@web.de>","Description"="Basic functions for analyzing qualitative and quantitative data based on R's default packages.","Depends"="R (>=3.0.0)","License"="GPL-2","Encoding"="UTF-8","LazyData"="true","RoxygenNote"="6.1.0","VignetteBuilder"="knitr"),
rproj=list("Version"="1.0","RestoreWorkspace"="No","SaveWorkspace"="No","AlwaysSaveHistory"="Default","EnableCodeIndexing"="Yes","Encoding"="UTF-8","AutoAppendNewline"="Yes","StripTrailingWhitespace"="Yes","BuildType"="Package","PackageUseDevtools"="Yes","PackageInstallArgs"="--no-multiarch --with-keep.source","PackageRoxygenize"="rd,collate,namespace"),
gitignore=c(".Rproj.user"),
rbuildignore=c(paste0("^",name,"\\.Rproj$"),"^\\.Rproj\\.user$")
){
wd=getwd()
if(!dir.exists(name))dir.create(name);
setwd(name)
writeList=function(list,file)write(paste0(names(list),(unlist(lapply(list,function(x)paste0(": ",x))))),file=file)
writeList(list=description,file="DESCRIPTION")
writeList(list=rproj,file=paste0(name,".Rproj"))
write(gitignore,file=".gitignore")
write(rbuildignore,file=".RBuildignore")
setwd(wd)
};
create(package.name,
description=list(
"Package"="qqBaseX",
"Title"="Basic functions for analyzing qualitative and quantitative data based on R's default packages.",
"Version"="0.4.7",
"Authors@R"="person(\"Andreas\", \"Fischer\", email = \"andreasfischer1985@web.de\", role = c(\"aut\", \"cre\"))",
"Maintainer"="'Andreas Fischer' <andreasfischer1985@web.de>",
"Description"=
paste(
"The qqBaseX package provides basic functions for assisting all steps of analyzing qualitative and quantitative data. It was written to extend R's default packages without introducing dependencies on other packages.",
"Besides enhanced variants of standard plots and methods (e.g., bp() or dotplot()), the qqBaseX package offers a number of convenience functions - like saveDevs(), to save open graphics devices in high resolution in various formats, or cols(), to easily create color series.",
"In addition, the package includes many functions for exploring datasets (e.g., plotDF() for data.frames or plotMAT() for matrices), functions for visualizing variables (e.g., spiderplot() or flowerplot()), functions for annotating plots (e.g., boxedText()) and functions for visualizing statistical analyses (e.g., plotLM() for linear models).",
"The package also includes model-agnostic functions for quantifying the influence of individual variables on predictions (for example, af.sensitivity() and delta()).",
"In addition, the package provides functions for sourcing data via web-scraping (e.g., scrapeHTML() or extractTable()) and for preprocessing data (e.g., prepareDF() for quantitative data analysis or vecToTDM() for qualitative data analysis)."
),
"Depends"="R (>= 3.0.0)",
"License"="GPL-2",
"Encoding"="UTF-8",
"LazyData"="true",
"RoxygenNote"="6.1.0",
"VignetteBuilder"="knitr")
);
setwd(package.name)
readLines("DESCRIPTION")
####################################
# set up R-functions
####################################
if(!dir.exists("R"))dir.create("R");
setwd("R")
###########################################
# Scraping
###########################################
n <- "vgrepl"
d <- paste0( "#' Function vgrepl\n",
"#' \n#' Variant of grepl that takes a vector of patterns.\n")
f <- function(pattern,x, sumFun=NULL, ...)
{f=Vectorize(grepl,vectorize.arg="pattern");erg=f(pattern=pattern,x=x,...);
if(!is.null(sumFun))erg=sumFun(erg);erg}
vgrepl=f #c=c("d","dasd");f(c("as","d"),c)
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n <- "getHTML";
#-------------
d <- paste0( "#' Function getHTML\n",
"#' \n#' Returns HTML from an URL obained via GET-request.\n",
"#' @param url Character string speficying a valid URL.\n",
"#' @param encoding Character value specifying the encoding. Defaults to \"UTF-8\".\n",
"#' @param save Logical value specifying whether the HTML-code should be saved to a txt-file.\n",
"#' @param filename Character value specifying the filename (if save is TRUE). If NULL (default) as.numeric(Sys.time()) is applied.\n",
"#' @param closeCon Logical value specifying whether to close open connections before and after scraping. defaults to F.\n",
"#' @param method Character value specifying the method. Defaults to \"libcurl\".\n",
"#' @param silent Logical value specifying whether to skip informative messages. Defaults to T.\n",
"#' @param curlHeaders Logical value specifying whether to apply curlHeaders. Defaults to F.\n",
"#' @param headers Logical value.\n",
"#' @param browseURL Locgical value specifying wether to open the URL in a web-browser. Defaults to F.\n",
"#' @details Returns HTML from an URL obained via GET-request. Assumes UTF-8 encoding by default. Returns a character element containing HTML-code.\n",
"#' @keywords scraping\n",
"#' @export\n",
"#' @examples\n",
"#' getHTML()")
f <- function(
url="https://scholar.google.de/citations?user=-TjY7oEAAAAJ&hl=de&oi=sra",
encoding="UTF-8",
save=F,
filename=NULL,
closeCon=F,
method="libcurl",
silent=T,
curlGetHeaders=F,
browseURL=F,
...){
if(closeCon){co=as.numeric(rownames(showConnections(all=T)));for(i in co[co>2]) close(getConnection(i));}
if(!silent)message(paste0("Trying to get html from ",url))
if(is.character(url)){
if(length(grep("(^http://|^https://|^ftp://|^file://)",url))==0) url=paste0("http://",url)
if(curlGetHeaders) message(paste(curlGetHeaders(url, verify=F),collapse=""))
if(browseURL) browseURL(url)
url=url(url,method=method,...)
}
html=paste(readLines(url,encoding=encoding), collapse="\n");
if(save) writeLines(
gsub("^<\n","",gsub("[ ]+"," ",paste0("<",strsplit(html,"<")[[1]]))),
paste0(ifelse(is.character(filename),filename,as.numeric(Sys.time())),".txt"))
if(closeCon){co=as.numeric(rownames(showConnections(all=T)));for(i in co[co>2]) close(getConnection(i));}
return(invisible(html))
}
getHTML=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n<-"scrapeHTML"
#-------------
d <- paste0( "#' Function scrapeHTML\n",
"#' \n#' Extracts Information from HTML.\n",
"#' @param html A character element containing HTML-code.\n",
"#' @param short Logical value specifying whether only lines with verbal information or link should be returned. Defaults to F.\n",
"#' @param edit Logical value specifying whether the data.frame should be plotted/edited.\n",
"#' @param save Logical value specifying whether the HTML-code should be saved to a csv-file.\n",
"#' @param plot Logical value specifying whether to plot the frequency of each HTML-tag found in the html-object.\n",
"#' @param filename Character value specifying the filename (if save is TRUE). If NULL (default) as.numeric(Sys.time()) is applied.\n",
"#' @details Extracts Information from HTML code (as returned by qqBaseX::getHTML, for example). Returns a data.frame with three columns: the first column contains html-code, the second column contains extracted verbal information, and the third column contains extracted links.\n",
"#' @keywords scraping\n",
"#' @export\n",
"#' @examples\n",
"#' scrapeHTML(getHTML())")
f <- function(
html,
short=F,
edit=T,
save=F,
plot=F,
filename=NULL){
if(length(html)>1)
if(length(dim(html))>2) stop("please provide HTML as a character vector!") else
if(length(dim(html))>1) { warning("two-dimensional input detected. Only first column is used."); html=paste(as.character(html[,1]),collapse=" ")} else html=paste(as.character(html),collapse=" ")
strings=gsub("(\n|\t)+"," ",gsub("[ ]+"," ",paste0("<",strsplit(html,"<")[[1]])))
if(plot){
s1=sort(table(gsub("(<[/]?|(>| ).*)","",strings))) # inspect all tags without parameters
bp(s1[s1>2],main2="Common Tags")
}
info=gsub("^[ ]*$","",gsub("^<[^<]*>","",strings))
links=character(length(info))
links[grep("href=[\"\'].*?[\"\']",strings)]=
gsub("[\"\'].*$","",gsub("^.*?href=[\"\']","",grep("href=[\"\'].*?[\"\']",strings,value=T)))
result=data.frame(entry=as.character(strings),info=as.character(info),links=as.character(links), stringsAsFactors=F)
if(short)result=result[nchar(as.character(result[,2]))>0|nchar(as.character(result[,3]))>0,]
if(edit)result=edit(result)
if(save) write.csv2(data.frame(result),paste0(ifelse(is.character(filename),filename,as.numeric(Sys.time())),".csv"))
return(invisible(result))
}
scrapeHTML=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n<-"subsetHTML"
#-------------
d <- paste0( "#' Function subsetHTML\n",
"#' \n#' Extracts a coherent subset of code from HTML-code.\n",
"#' @param html A character element containing HTML-code.\n",
"#' @param tag Character element specifying the the subsets of interest. Defaults to \"div\".\n",
"#' @param pattern Regular expression further specifying subsets of interest. If NULL (default) equals tag.\n",
"#' @param edit Logical value specifying whether the data.frame should be plotted/edited.\n",
"#' @param save Logical value specifying whether the HTML-code should be saved to a csv-file.\n",
"#' @param plot Logical value specifying whether to plot the frequency of each HTML-tag found in the html-object.\n",
"#' @param filename Character value specifying the filename (if save is TRUE). If NULL (default) as.numeric(Sys.time()) is applied.\n",
"#' @param trim Logical value specifying whether to trim text. Defaults to T.\n",
"#' @details Extracts a coherent subset of code from HTML-code (as returned by qqBaseX::getHTML, for example).\n",
"#' @keywords scraping\n",
"#' @export\n",
"#' @examples\n",
"#' subsetHTML(getHTML(\"https://jobs.meinestadt.de/nuernberg/suche?words=Wissenschaftlicher%20Mitarbeiter\",tag=\"div\",pattern=\"class=\\\"m-resultListEntries__content\\\"\"))")
f <- function (
html,
tag="div",
pattern = NULL,
edit=F,
save = F,
plot=F,
filename = NULL,
trim=T) {
if(length(html)>1)
if(length(dim(html))>2) stop("please provide HTML as a character vector!") else
if(length(dim(html))>1) { warning("two-dimensional input detected. Only first column is used."); html=paste(as.character(html[,1]),collapse=" ")} else html=paste(as.character(html),collapse=" ")
start = paste0("<",tag,"[\n\r> ]")
end = paste0("</",tag,">")
if(is.null(pattern))pattern=start
strings = gsub("[ ]+", " ", paste0("<", strsplit(html, "<")[[1]]))
if(plot){
s1=sort(table(gsub("(<[/]?|(>| ).*)","",strings))) # inspect all tags without parameters
bp(s1[s1>2],main2="Common Tags")
}
infos = gsub("^[ ]*$", "", gsub("^<[^<]*>", "", strings))
links = character(length(infos))
links[grep("href=[\"'].*?[\"']", strings)] = gsub("[\"'].*$","", gsub("^.*?href=[\"']", "", grep("href=[\"'].*?[\"']", strings, value = T)))
loc.pat = grep(pattern, strings)
loc.div1 = grep(start, strings)
loc.div2 = grep(end, strings)
result0 = character(0);result1 = character(0);result2 = character(0);result3 = character(0)
for (i1 in loc.pat) {
loc.div3 = sort(c(loc.div1[which(loc.div1 > i1)], loc.div2[which(loc.div2 > i1)]))
i2 = i1
for (i in loc.div3) { i2 = i; if (length(loc.div1[which(loc.div1 > i1 & loc.div1 <= i)]) < length(loc.div2[which(loc.div2 > i1 & loc.div2 <= i)])) break; }
string = paste(strings[i1:i2], collapse = "\n")
info = paste(infos[i1:i2], collapse = "\n")
link = paste(links[i1:i2], collapse = "\n")
text = gsub("^( )*(\n)*( )*(\n)*", "", gsub("(\n)+( )*(\n)*", "\n", gsub("<.*?>", "", string)))
if(trim==T){
result0 = c(result0, gsub("[\n]+","\n",qqBaseX::trim(string)))
result1 = c(result1, gsub("[\n]+","\n",qqBaseX::trim(text)))
result2 = c(result2, gsub("[\n]+","\n",qqBaseX::trim(info)))
result3 = c(result3, gsub("[\n]+","\n",qqBaseX::trim(link)))
} else {
result0 = c(result0, (string))
result1 = c(result1, (text))
result2 = c(result2, (info))
result3 = c(result3, (link))
}
}
result=data.frame(entry=result0, info=result2, links=result3, stringsAsFactors=F) #text=result1
result=result[grep(paste0("^",start),result[,1]),]
if(edit) result=edit(result)
if (save){
write.csv2(data.frame(result),paste0(ifelse(is.character(filename),filename,as.numeric(Sys.time())),".csv"))
}
return(invisible(result))
}
subsetHTML=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n<-"extractTable"
#-------------
d <- paste0( "#' Function extractTable\n",
"#' \n#' Extracts table as data.frames from multiple lines of text.\n",
"#' @param x A character element containing all the text toextract the table from (or a character vector containing one text-line per element).\n",
"#' @param reg.up Regular expression spefifying the top of the table. Defaults to NULL.\n",
"#' @param reg.down Regular expression spefifying the bottom of the table. Defaults to NULL.\n",
"#' @param reg.left Regular expression spefifying the bottom of the table. Defaults to \"^\".\n",
"#' @param reg.right Regular expression spefifying the bottom of the table. Defaults to \"$\"\n",
"#' @param reg.fix Regular expression spefifying the bottom of the table. Defaults to NULL.\n",
"#' @param header Logical value that specifies, whether to treat first row and column as row- and column-names. Defaults to F.\n",
"#' @param trim Logical value that specifies, whether to trim entries. Defaults to T.\n",
"#' @param convert Logical value that specifies, whether to convert table to numeric (after correcting for notation in case correctNotation is set to T). Please use with care, if table contains non-numeric information. Defaults to T.\n",
"#' @param correctNotation Logical value that specifies, whether to correct for the fact that entries use commata instead of dots. Erases all dots in all entries and subsequently replaces commata by dots. Defaults to F.\n",
"#' @details Extracts table as data.frames from multiple lines of text. Columns are assumed to be separated by whitespaces that are placed at the same position in each line. Please make sure that headers don't span multiple columns or rows.\n",
"#' @keywords scraping\n",
"#' @export\n")
f=function(
x,
reg.up=NULL,
reg.down=NULL,
reg.left="^",
reg.right="$",
reg.fix=NULL,
header=F,
trim=T,
convert=F,
correctNotation=F){
if(length(x)==1) x=strsplit(x,"(\r\n|\r|\n)")[[1]]
trimIt=function(x)gsub("(^[ ]+|[ ]+$)","",x);
if(!is.null(reg.up)){
lines=(grep(reg.up,x)[1]):(grep(reg.down,x)[1]-1)
x=x[lines]
rows=(unlist(gregexpr(reg.left,x[1]))[1]):(unlist(gregexpr(reg.right,x[1]))[1])
x=substr(x,min(rows),max(rows));
}
cells=x[nchar(x)>0&!(grepl("^[ ]+$",x))] #streiche leere zeilen
t=data.frame(sapply(cells,function(y)paste0(y,paste(rep(" ",max(nchar(cells))-nchar(y)),collapse=""))))
t2=strsplit(as.character(t[,1]),"")
d1=data.frame(t2[[1]]);for(i in 2:length(t2))d1=data.frame(d1,t2[[i]])
t2=t(d1)
w=c(which(colSums(t2==" ")==max(colSums(t2==" "))),dim(t2)[2])
e=list();
for(i in 1:length(w))e[[i]]=apply(data.frame(t2[,ifelse(i==1,1,w[i-1]):w[i]]),1,function(x)paste(x,collapse=""))
erg=data.frame(e[[1]]);
for(i in 2:length(w))erg=apply(data.frame(erg,e[[i]]),2,as.character)
if(header){
colnames(erg)=trim(as.character(erg[1,]))
rownames(erg)=trim(as.character(erg[,1]))
erg=erg[-1,-1]
} else { colnames(erg)=1:dim(erg)[2];rownames(erg)=1:dim(erg)[1];}
erg=erg[,!colSums(erg==" ")==max(colSums(erg==" "))];
rn=rownames(erg);
if(correctNotation)erg=apply(erg,2,function(x)gsub("[%.]","",x)) #erase % and dots
if(correctNotation)erg=apply(erg,2,function(x)gsub("[,]",".",x)) #change comm to dots
if(!is.null(reg.fix))erg=gsub(reg.fix,"",erg)
if(convert){erg=apply(erg,2,as.numeric);rownames(erg)=rn}
if(trim)return(trimIt(erg)) else return(erg)
}
extractTable=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n <- "scrapeJDDM"
d <- paste0(
"#' Function scrapeJDDM\n",
"#' \n#' Downloads and returns data and metadata from the database of the Journal of Dynamic Decision Making.\n",
"#' @param plot Logical value specifying wether to plot data on reads and downloads.\n",
"#' @param urls Character vector specifying the URLs of the individual issues to scrape.\n",
"#' @param url2 Character value specifying the URL of global journal statistics.\n",
"#' @param plot Logical value specifying wether to plot data on reads and downloads.\n",
"#' @details Downloads and returns data and metadata from the database of the Journal of Dynamic Decision Making.\n",
"#' @keywords scraping\n",
"#' @export\n",
"#' @examples\n",
"#' s=scrapeJDDM();"
);
f<-function(
plot=T,
urls=paste0("https://journals.ub.uni-heidelberg.de/index.php/jddm/issue/view/",c(3269,2836,2269,3694,4432)),
url2="https://journals.ub.uni-heidelberg.de/cgi-bin/oastats.cgi?repo=ojs;from_date=2015-09-29%2021:39:27;id=jddm:"
){
article.ids = character(0)
all.authors = character(0)
authors = character(0)
years = character(0)
article.labels = character(0)
for (url in urls) {
html0 = gsub("(\t|\n)", "", paste(readLines(url, encoding = "UTF-8"),
collapse = "\n"))
links = matchAll(html0, "https://journals.ub.uni-heidelberg.de/index.php/jddm/article/view/[0-9/]*\\\">PDF")[[1]][,
1]
article.ids = c(article.ids, gsub("(.*view/|\\\">PDF)",
"", links))
all.authors = c(all.authors, gsub("</div>.*", "", strsplit(html0,
"(\"authors\\\">)")[[1]])[-1])
authors = paste0(gsub(",.*", "", all.authors), " et al.")
authors[grep("Fischer(.*)Holt(.*)Funke", all.authors)] = "Editoral"
years = c(years, rep(gsub("(.*[(]|[)])", "", matchOne(html0,
"<title>Vol [0-9]* \\([0-9]*\\)"))[, 1], length(links)))
}
article.labels = paste0(authors, " (", years, ")")
names(article.labels) = article.ids
html = list()
for (i in 1:length(article.ids)) {
html[as.character(article.ids[i])] = paste(readLines(paste0(url2,
gsub("/.*", "", article.ids[i]), ";lang=ende;overlay=1"),
encoding = "UTF-8"), collapse = "\n")
message(article.ids[i])
}
html = unlist(html)
current.year = as.numeric(gsub("-.*", "", (Sys.Date())))
span = current.year - 2015 + 1
results = list()
for (i in 1:length(html)) {
months = paste(paste0(">", c("Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
"Dec"), "<"), collapse = "|")
df = data.frame(c("Intro", matchAll(html[i], months)[[1]]),
strsplit(as.character(html[i]), months))
df[, 2] = gsub("<table class=\\\"stats\\\"><tr><th>20[0-9][0-9]</th>",
"", df[, 2])
numbers = sapply(matchAll(df[, 2], ">[0-9]+<"), function(x) as.numeric(gsub("[<>]",
"", c(x[1:2]))))[, -1]
if (is.null(dim(numbers)))
numbers = as.matrix(numbers)
colnames(numbers) = gsub("[<>]", "", df[-1, 1])
rownames(numbers) = c("Downloads", "Frontdoor")
mo = dim(numbers)[2]
numbers = cbind(numbers, matrix(NA, nrow = 2, ncol = 24 -
mo))
colnames(numbers) = paste(colnames(numbers), c(rep(current.year,
12), rep(current.year - 1, 12)))
st = matchAll(df[, 2], ">[0-9]+<")
prior = as.numeric(gsub("[<>]", "", st[[length(st)]][-c(1:2),
1]))
prior = c(prior, rep(NA, 2 * (as.numeric(gsub("-.*",
"", (Sys.Date()))) - 2014) - length(prior)))
numbers = cbind(numbers, t(data.frame(prior[seq(1, length(prior),
2)], prior[seq(1, length(prior), 2) + 1])))
colnames(numbers)[25:(24 + span)] = as.numeric(gsub("-.*",
"", (Sys.Date()))):2015
results[[as.character(article.ids[i])]] = numbers
}
m = matrix(ncol = (24 + span))
for (i in 1:length(results)) m = rbind(m, results[[i]])
m = m[-1, ]
rownames(m) = paste(rownames(m), rep(article.ids, each = 2))
if (as.numeric(gsub("(^[0-9]*-|-[0-9]*$)", "", Sys.Date())) <
12) {
shift = which(!is.na(m[, 1]))
m[shift, 13:24] = m[shift, 1:12]
m[shift, 1:12] = NA
m = m[, first(which(dim(m)[1] != colSums(is.na(m)))):dim(m)[2]]
}
names(article.labels) = article.ids
current.year = as.numeric(gsub("-.*", "", (Sys.Date())))
years.JDDM = (as.numeric(gsub("-.*", "", (Sys.Date()))) -
2014)
entryNo = 2 * 12 + years.JDDM - 2
downloads = m[seq(1, dim(m)[1], 2), dim(m)[2]:1]
frontdoor = m[seq(1, dim(m)[1], 2) + 1, dim(m)[2]:1]
downloads.per.year = m[seq(1, dim(m)[1], 2), dim(m)[2]:1][,
1:years.JDDM]
frontdoor.per.year = m[seq(1, dim(m)[1], 2) + 1, dim(m)[2]:1][,
1:years.JDDM]
frontdoor.per.year[is.na(frontdoor.per.year)] = 0
downloads.per.year[is.na(downloads.per.year)] = 0
df = data.frame(article.ids, article.labels, all.authors,
authors, years, download.link = paste0("https://journals.ub.uni-heidelberg.de/index.php/jddm/article/download/",
article.ids), downloads, frontdoor)
if (F) {
if (any(rowSums(is.na(downloads[, (current.year - 2013):dim(downloads)[2]])) >
11) | any(rowSums(is.na(frontdoor[, (current.year -
2013):dim(frontdoor)[2]])) > 11))
warning("only a subset of papers is returned. please try again next month")
df = df[(rowSums(is.na(downloads[, (current.year - 2013):dim(downloads)[2]])) <
12 & rowSums(is.na(frontdoor[, (current.year - 2013):dim(frontdoor)[2]])) <
12), ]
}
if (plot) {
downloads2 = downloads[, colnames(downloads) != as.character(current.year -
1) & colnames(downloads) != as.character(current.year)]
rownames(downloads2) = article.labels
downloads2 = downloads2[order(rowSums(downloads2, na.rm = T),
decreasing = T)[1:min(dim(downloads2)[1], 25)], ]
dev.new(width = 10, height = 7)
plotMAT(downloads2, main = "Cumulation of Downloads",
cumsum = T)
frontdoor2 = frontdoor[, colnames(frontdoor) != as.character(current.year -
1) & colnames(frontdoor) != as.character(current.year)]
rownames(frontdoor2) = article.labels
frontdoor2 = frontdoor2[order(rowSums(frontdoor2, na.rm = T),
decreasing = T)[1:min(dim(frontdoor2)[1], 25)], ]
dev.new(width = 10, height = 7)
plotMAT(frontdoor2, main = "Cumulation of Reads", cumsum = T)
}
return(df)
}
scrapeJDDM=f;
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
#g1=getHTML("https://statistik.ub.uni-heidelberg.de/oa_statistik/doc_id/period/showmonth/?doc_id=ojs:jddm:69298")
#g2=getHTML("https://statistik.ub.uni-heidelberg.de/oa_statistik/doc_id/country/?doc_id=ojs:jddm:69298")
#g3=getHTML("https://journals.ub.uni-heidelberg.de/cgi-bin/oastats.cgi?repo=ojs;from_date=2015-09-29%2021:39:27;id=jddm:69298;lang=ende;overlay=1")
#strsplit(g1,"\\{")
###########################################
# Plotting
###########################################
n="saveDevs"
d <- paste0(
"#' Function saveDevs\n",
"#' \n#' Saves each element of dev.list() to a graphical device such as pdf, png or similar.\n",
"#' @param filename Character vector containing file names.\n",
"#' @param width Width of the devices. If NA (default), width of the devices is left unchanged.\n",
"#' @param height Height of the devices. If NA (default), height of the devices is left unchanged.\n",
"#' @param dev Graphical device (currently, pdf, win.metafile, png, bmp, jpg and tiff are supported).\n",
"#' @param units Parameter passed to dev.copy. Defaults to \"in\". Is ignored if dev==pdf.\n",
"#' @param res Resolution (dots per inch) of the devices. Defaults to 300. Is ignored if dev==pdf.\n",
"#' @param mess Logical value specifying if a message should be printed after saving the devices. Defaults to T.\n",
"#' @param close Logical value specifying whether to close devices after saving them.\n",
"#' @details Saves each element of dev.list() to a graphical device such as pdf, png or similar.\n",
"#' @keywords plotting\n",
"#' @export\n",
"#' @examples\n",
"#' saveDevs();"
);
f <- function (
filename = NA,
width = NA,
height = NA,
dev = png,
units = "in",
res = 300,
mess = T,
close = F,
...){
n = deparse(substitute(dev))
n[n == "win.metafile"] = "emf"
l = dev.list()
if (length(l)==0) {warning("No device open.");return(invisible());}
if (length(filename) != length(l)) filename = rep(filename[1], length(l))
if (length(width) != length(l)) width = rep(width[1], length(l))
if (length(height) != length(l)) height = rep(height[1], length(l))
filename[is.na(filename)]=""
if(sum(table(match(filename, levels(as.factor(filename))))>1)>0)filename=paste(filename,1:length(filename))
if(filename[1]=="" & length(filename)==1) filename="Plot"
filename[grepl(paste0("[.]",n,"$"),filename)==F] = paste0(filename[grepl(paste0("[.]",n,"$"),filename)==F], ".", n)
for (i in 1:length(l)) {
d = l[i]
dev.set(d)
width1 = width[i]
height1 = height[i]
filename1 = filename[i]
if (is.na(width1))width1 = (dev.size()[1])
if (is.na(height1))height1 = (dev.size()[2])
if (length(grep("(bmp|png|jpg|tiff)", n)) > 0) dev.copy(dev, filename1,
width = width1, height = height1, units = units,res = res, ...)
else if (length(grep("(pdf|emf)", n)) > 0)
dev.copy(dev, filename1, width = width1, height = height1, ...)
else dev.copy(dev, filename1, width = width1, height = height1, ...)
dev.off()
}
if (close) graphics.off()
if (mess) message(ifelse(length(l) > 1, paste0(length(l), " devices saved to\n", getwd()), paste0(length(l), " device saved to\n", getwd())))
}
saveDevs=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n="plotXY"
#-------------
d <- paste0( "#' Function plotXY\n",
"#' \n#' Plots bivariate correlation based on two numeric vectors.\n",
"#' @param x Numeric vector.\n",
"#' @param y Numeric vector of the same length as x.\n",
"#' @param complexity Numeric value specifying the amount of nonlinearity modelled. Defaults to 0 (i.e., a linear model).\n",
"#' @param rep.nnet Numeric value specifying the number of nnet-objects to choose the best model from.\n",
"#' @param attrModel Logical value specifying whether to add the model as an attribute to the object returned.\n",
"#' @param na.rm Logical value indicating whether missing values should be skipped. Defaults to T.\n",
"#' @param color1 Color of points in the scattergram. Defaults to rgb(0,0,0,.7).\n",
"#' @param color2 Color of the regression line. Defaults to rgb(0,0,1).\n",
"#' @param color3 Color of the prediction interval. Defaults to rgb(0,0,1,.2).\n",
"#' @param ... additional parameters passed to the plot function.\n",
"#' @details Plots scattergram and bivariate correlation based on two numeric vectors.\n",
"#' @keywords plotting\n",
"#' @export\n",
"#' @examples\n",
"#' plotXY()")
f<- function (
x = NULL,
y = NULL,
complexity = 0,
rep.nnet = 10,
attrModel = T,
na.rm = T,
color1 = rgb(0, 0, 0, 0.7),
color2 = rgb(0, 0, 1),
color3 = rgb(0, 0, 1, 0.2),
xlab = "x",
ylab = "y",
axes = T,
add = F,
main = NA,
sub = NA,
pch = 16,
lwd = 2,
cex = 0.7,
cex.sub = 0.7,
generalize = F,
main1 = NULL,
main2 = NULL,
main3 = NULL,
mar=NA,
adj.main1 = 0,
adj.main2 = 0,
adj.main3 = 0,
col.main1 = "black",
col.main2 = "black",
col.main3 = "black",
cex.main1 = 1.2,
cex.main2 = 1.2,
cex.main3 = 1.2,
font.main1 = 1,
font.main2 = 2,
font.main3 = 4,
...)
{
if (is.null(sub))
sub = ifelse(complexity == 0, "Shaded area represents 95%-confidence interval.",
"Shaded area represents 95%-prediction interval.")
if (is.null(x) & is.null(y)) {
x = rnorm(100)
y = rnorm(100)
}
mar0 = NULL
if (is.numeric(mar)) {
mar0 = par("mar")
par(mar = mar)
}
data = data.frame(x, y)
if (na.rm == T) data = data[complete.cases(data), ]
data0 = data
data = data.frame(scale(data))
colnames(data) = colnames(data0)
nnet = NULL
lm = NULL
if (complexity>0)
if (length(grep("^quantqual$", (installed.packages()[, "Package"]))) == 0) {
complexity=0;
warning("complexity set to 0 because quantqual-package is not installed.\nYou may install it via devtools::install_github(\"AndreasFischer1985/quantqual\")")
}
if (complexity > 0) {
if (!generalize)
nnet = quantqual::nnets(data, "y", size = complexity, linout = T, rep.nnet = rep.nnet)[[1]]
else nnet = quantqual::af.nnet(data, "y", size = complexity, decay = NULL, linout = T, rep.nnet = rep.nnet)
xTrain = data[colnames(data) != "y"]
yTrain = data["y"]
p = quantqual::predintNNET(nnet, xTrain, yTrain, main = main, sub = sub,
color1 = color1, color2 = color2, color3 = color3,
xlab = xlab, ylab = ylab, axes = axes, plot = F)
p = p[order(data[, 1]), ]
len = dim(p)[1]
in1 = sort(data[, 1])
ou1 = p[, 1]
inner = p[, 2]
outer = p[, 3]
}
else {
l1 = lm(data[, 2] ~ data[, 1])
lm = l1
co1 = confint(l1)
len = 100
in1 = seq(min(data[, 1]), max(data[, 1]), length.out = len)
ou1 = in1 * coef(l1)[2] + coef(l1)[1]
ou2 = data.frame(in1 * co1[2, 1] + co1[1, 1], in1 * co1[2,
2] + co1[1, 2], in1 * co1[2, 1] + co1[1, 2], in1 *
co1[2, 2] + co1[1, 1])
inner = apply(ou2, 1, min)
outer = apply(ou2, 1, max)
}
unscale = function(x, m, s) x * s + m
in1 = unscale(in1, mean(data0[, 1], na.rm = T), sd(data0[, 1], na.rm = T))
ou1 = unscale(ou1, mean(data0[, 2], na.rm = T), sd(data0[, 2], na.rm = T))
inner = unscale(inner, mean(data0[, 2], na.rm = T), sd(data0[, 2], na.rm = T))
outer = unscale(outer, mean(data0[, 2], na.rm = T), sd(data0[, 2], na.rm = T))
if (add == F) plot(data0[, 1], data0[, 2], xlab = xlab, ylab = ylab, main = main, type = "n", axes = axes, ...)
if (add == F) if (!is.null(sub)) title(sub = sub, cex.sub = cex.sub)
polygon(c(in1, in1[length(in1):1]), c(inner, outer[length(outer):1]), col = color3[1], border = NA)
if(length(data0[, 1])!=length(color1))color1=color1[1]
points(data0[, 1], data0[, 2], pch = pch, col = color1)
lines(in1, ou1, , col = color2[1], lwd = lwd)
dat = data.frame(predictor = in1, prediction = ou1, lower.bound = inner, upper.bound = outer)
if (attrModel)
if (!is.null(nnet)) attr(dat, "model") = nnet
else attr(dat, "model") = lm
if (!is.null(main1))
title(main1, line = 1, adj = adj.main1, cex.main = cex.main1, col = col.main1, font.main = font.main1)
if (!is.null(main2))
title(main2, line = 2, adj = adj.main2, cex.main = cex.main2, col = col.main2, font.main = font.main2)
if (!is.null(main3))
title(main3, line = 3, adj = adj.main3, cex.main = cex.main3, col = col.main3, font.main = font.main3)
if (is.numeric(mar)) par(mar = mar0)
return(invisible(dat))
}
plotXY=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n <- "cols"
#------------
d <- paste0(
"#' Function cols\n",
"#' \n#' Returns a vector of colors of a certain length.\n",
"#' @param num Number of colors to return or a numeric vector containing indices of colors. Defaults to 1.\n",
"#' @param col2 Character vector specifying the darker color of the specturm to be returned.\n",
"#' @param col1 Character vector specifying the lighter color of the specturm to be returned.\n",
"#' @details Returns a vector of colors of a certain length. If col1 and col2 are NULL (default) a rainbow palette is returned. If col2 is specified, col1 is set to \"white\". If col1 is specified, col2 is set to \"black\". In addition to regular color labels, the cols-function accepts some pre-defined color-labels (such as \"jddm\" or \"jddmLight\" for the Logo-colors of the Journal of Dynamic Decision Making). If num is a numeric vector, the color palette will have max(num) colors, the number of colors returned equals length(num), and num itself is applied as a vector of indices for the color palette returned. \n",
"#' @keywords plotting\n",
"#' @export\n",
"#' @examples\n",
"#' bp(1:10,col=cols(10,\"jddm\"))"
);
f<-function(num=1,col2=NULL,col1=NULL){
if(is.null(num))num=1
if(length(num)>1){num=num[1];warning("Please provide a single number for num (or set col1 and col2 to NULL). Only first element is used.");}
if(length(col1)>1){col1=col1[1];warning("Please provide a single color name for col1. Only first element is used.");}
if(length(col2)>1){col2=col2[1];warning("Please provide a single color name for col2. Only first element is used.");}
if(!is.numeric(num)&is.null(col1)&is.null(col2)){col1=num;col2=num;num=1}
if(is.numeric(num)&is.null(col1)&is.null(col2))if(length(num)>1){num[num<1]=1;return(rainbow(max(num))[num]);} else return(rainbow(num))
if(is.null(col1))col1="white";
if(is.null(col2))col2="black"
x="jddm";y=rgb(135/255,44/255,40/255); if(col1==x)col1=y;if(col2==x)col2=y;
x="jddmLight";y=rgb(118/255,119/255,118/255);if(col1==x)col1=y;if(col2==x)col2=y;
x="fbb";y=rgb(0/255,84/255,122/255); if(col1==x)col1=y;if(col2==x)col2=y;
x="fbbLight";y=rgb(217/255,231/255,239/255); if(col1==x)col1=y;if(col2==x)col2=y;
x="bst";y=rgb(0/255,50/255,100/255); if(col1==x)col1=y;if(col2==x)col2=y;
x="ba";y=rgb(226/255,0/255,26/255); if(col1==x)col1=y;if(col2==x)col2=y;
if(length(num)>1){num[num<1]=1;return(colorRampPalette(c(col1,col2))(max(num))[num]);}
if(num==1)return(col2)
return(colorRampPalette(c(col1,col2))(num));
}
cols=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n<-"cols2"
#------------
d <- paste0(
"#' Function cols2\n",
"#' \n#' Returns a vector of transparent colors based on a vector of colors.\n",
"#' @param col Character vector specifying the colors to be transformed.\n",
"#' @param transparency Numberic value specifying the transparency of the colors to be returned. Defaults to .3\n",
"#' @details Returns a vector of transparent colors based on a vector of colors.\n",
"#' @keywords plotting\n",
"#' @export\n",
"#' @examples\n",
"#' cols2(cols(10,\"jddm\")))"
);
f<-function(col,transparency=.7){
if(length(transparency)!=1)transparency=F
if(is.na(transparency)|!is.numeric(transparency))transparency=F
if(transparency<0)transparency=F
ifelse(transparency==F,
list(sapply(col,function(x)qqBaseX::cols(3,x,"white")[2])),
list(apply(col2rgb(col),2,function(x)rgb(x[1]/255,x[2]/255,x[3]/255,1-transparency))))[[1]]
}
cols2=f;
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n="decollide"
#-------------
d <- paste0(
"#' Function decollide\n",
"#' \n#' Returns a matrix with coordinates and text for plotting texts without collisions.\n",
"#' @param x Numeric vector containing x-coordinates of text elements.\n",
"#' @param y Numeric vector containing x-coordinates of text elements.\n",
"#' @param text Character vector containing text-elements to be plotted.\n",
"#' @param jitter Logical value specifying whether to add a small random component after each step.\n",
"#' @param cex Numeric value specifying the relative font size of the text. Defaults to 1.\n",
"#' @param frame Numeric value specifying the relative font size of an invisible frame around the text. Defaults to 1.5\n",
"#' @param lock.x Logical value specifying whether to skip shifts on the x-axis. Defaults to F.\n",
"#' @param lock.y Logical value specifying whether to skip shifts on the y-axis. Defaults to F.\n",
"#' @param verbose Logical value specifying whether to give information on the process after each step.\n",
"#' @param cex Numeric value specifying the maximum number of steps. Defaults to 100.\n",
"#' @details Returns a matrix with coordinates and text for plotting texts without collisions. Iteratively shifts text elements until all collisions are eliminated or the maximum number of repetitions is reached.\n",
"#' @keywords plotting\n",
"#' @export\n",
"#' @examples\n",
"#' set.seed(0);decollide(x=rnorm(10),y=rnorm(10),text=paste0(1:10,\":\",round(rnorm(10),3)),cex=1,font=1,plot=T)"
);
f<-function(x,y,text,jitter=F,cex=1,font=1,frame=1.5,plot=F,lock.x=F,lock.y=F,verbose=F,repetitions=100){
x0=x;y0=y;
if(plot){xrange=max(x)-min(x);yrange=max(y)-min(y);plot(x,y,type="n",xlim=c(min(x)-xrange/2,max(x)+xrange/2),ylim=c(min(y)-yrange/2,max(y)+yrange/2));text(x,y,text,font=font,cex=cex);}else
xrange=par("usr")[2]-par("usr")[1];yrange=par("usr")[4]-par("usr")[3];
sw=strwidth(text,font=font,cex=cex*frame,units="user");
sh=strheight(text,font=font,cex=cex*frame,units="user");
co=cbind(x-sw/2,x+sw/2,y-sh/2,y+sh/2)
m=matrix(0,nrow=dim(co)[1],ncol=dim(co)[1])
for(i in 1:repetitions){
for(i in 1:dim(co)[1])for(j in 1:dim(co)[1])if(i!=j){
col=co[j,1]<=co[i,2]&co[j,2]>=co[i,1]&((co[j,3]<=co[i,4]&co[j,4]>=co[i,3])|(co[j,4]>=co[i,3]&co[j,3]<=co[i,4]))
m[i,j]=col;
if(col){
if(x[i]>=x[j]&!lock.x) x[i]=x[i]+xrange/100;
if(x[i]<x[j]&!lock.x) x[i]=x[i]-xrange/100;
if(y[i]>=y[j]&!lock.y) y[i]=y[i]+yrange/100;
if(y[i]<y[j]&!lock.x) y[i]=y[i]-yrange/100;
if(jitter){
co=cbind(x-sw/2,x+sw/2,y-sh/2,y+sh/2)
col=co[j,1]<co[i,2]&co[j,2]>co[i,1]&((co[j,3]<co[i,4]&co[j,4]>co[i,3])|(co[j,4]>co[i,3]&co[j,3]<co[i,4]))
if(col){
if(abs(x[i]-x[j])>=0&!lock.x) x[i]=x[i]+ifelse(jitter,rnorm(1,sd=sd(x)/100),0);
if(abs(y[i]-y[j])>=0&!lock.y) y[i]=y[i]+ifelse(jitter,rnorm(1,sd=sd(y)/100),0);
}
}
}
co=cbind(x-sw/2,x+sw/2,y-sh/2,y+sh/2)
};if(verbose)message(sum(m)/2); if(plot){plot(x,y,type="n",xlim=c(min(x)-xrange/2,max(x)+xrange/2),ylim=c(min(y)-yrange/2,max(y)+yrange/2));text(x,y,text,font=font,cex=cex);}
if(sum(m)/2==0)break;
}
return(data.frame(x,y,text))
}
decollide=f;
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n="mar"
d <- paste0(
"#' Function mar\n",
"#' \n#' Returns margins of plots given numeric vectors to add and/or multiply, and/or a set of labels for each axis.\n",
"#' @param mar Numeric vector containing default margins. Defaults to c(5.1, 4.1, 4.1, 2.1).\n",
"#' @param mar1 Numeric vector to be multiplied with mar. Defaults to c(1,1,1,1).\n",
"#' @param mar0 Numeric vector to be added to the product of mar and mar1. Defaults to c(0,0,0,0).\n",
"#' @param labels1 Character vector containing labels for axis 1 (bottom).\n",
"#' @param labels2 Character vector containing labels for axis 2 (left).\n",
"#' @param labels3 Character vector containing labels for axis 3 (up).\n",
"#' @param labels4 Character vector containing labels for axis 4 (right).\n",
"#' @param set Logical value specifying whether to set the margins after determining them. Defaults to T\n",
"#' @details Returns margins of plots given numeric vectors to add and/or multiply, and/or a set of labels for each axis.\n",
"#' @keywords plotting\n",
"#' @export\n",
"#' @examples\n",
"#' mar();"
);
f=function(mar=c( 5.1,4.1,4.1,2.1), mar1=c(1,1,1,1), mar0=c(0,0,0,0), labels1=NULL, labels2=NULL, labels3=NULL, labels4=NULL, labelFactor=3,set=T){
if(is.null(mar))if(length(dev.list())>0) {mar=par("mar")} else mar=c( 5.1,4.1,4.1,2.1)
if(!is.null(labels1)) mar[1]=mar[1]+max(strwidth(labels1,units="inches")*labelFactor,na.rm=T)
if(!is.null(labels2)) mar[2]=mar[2]+max(strwidth(labels2,units="inches")*labelFactor,na.rm=T)
if(!is.null(labels3)) mar[3]=mar[3]+max(strwidth(labels3,units="inches")*labelFactor,na.rm=T)
if(!is.null(labels4)) mar[4]=mar[4]+max(strwidth(labels4,units="inches")*labelFactor,na.rm=T)
mar=mar*mar1
mar=mar+mar0
if(set!=F) par("mar"=mar)
return(invisible(mar))
}
mar=f
write(paste0(d,"\n\n",n," <- ",paste(deparse(f),collapse="\n")),file=paste0(n,".r"))
n <- "bp"
#------------
d <- paste0(
"#' Function bp\n",
"#' \n#' Custom barplot with labeled bars.\n",
"#' @param x Numeric vector, matrix or data.frame containing the values to be displayed.\n",
"#' @param sd Numeric vector, matrix or data.frame of same format as x containing standard deviations.\n",
"#' @param cex Size of axis fonts. Defaults to 1.\n",
"#' @param beside Logical value indicating if bars should be placed next to each other. Defaults to T.\n",
"#' @param horiz Logical value indicating if bars should be placed horizontal. Defaults to F.\n",
"#' @param breakLabels Logical value indicating if labels of bars should be tranformed by qqBaseX::labelbreaker. Defaults to F.\n",
"#' @param add.numbers Logical value indicating if numbers should be placed above bars. Defaults to F.\n",
"#' @param ndigits Numeric value specifying the number of digits to be plotted (if add.numbers==T). Defaults to 2.\n",
"#' @param ncex Size of fonts. If NA (default) is set to cex.\n",
"#' @param nsrt Numeric value specifying the rotation of the numbers (between 0 and 360 degrees). Defaults to 0.\n",
"#' @param npos Numeric value specifying the position of numbers. If NA (default) it is determined automatically.\n",
"#' @param ncol Vector containing the color of bars. Defaults to \"black\".\n",
"#' @param sdcol Vector containing the color of arrows. Defaults to \"grey\".\n",
"#' @param grid Logical value indicating whether to plot a grid. Defaults to T.\n",
"#' @param plot Logical value indicating whether to plot the barplot. Defaults to T.\n",
"#' @param main Character vector with one element containing the barplot's title. Defaults to NULL\n",
"#' @param sub Character vector with one element containing the barplot's subtitle. Defaults to NULL\n",
"#' @param xlim.factor Numeric value for adding extra space to the right of the barplot (if a legend is provided). Defaults to 1.5\n",
"#' @param xlim Numeric vector containing xlim.\n",
"#' @param las Numeric value specifying the rotation of the y-axis (0 for 90 percent rotation, 1 for 0 percent rotation). Defaults to 1.\n",
"#' @param srt Numeric value specifying the rotation of the x-axis (between 0 and 360 degrees). Defaults to 45.\n",
"#' @param names.arg Character vector containing names of bars. If NULL (default) colnames of x will be applied as names.arg.\n",
"#' @param legend.text Legend text. Set to NA or to F to supress legend. If NULL (default) rownames of x will be applied as legend.text.\n",
"#' @param optimize.legend Logical or character value. If T (Default), the legend is shifted to the right if overlapping with bars (as long as no args.legend are provided). If a position is provided instead (\"bottom\", \"bottomleft\", \"left\",\"topleft\",\"top\",\"topright\",\"right\",\"bottomright\") the legend will be placed and shifted accordingly. Adding a \"1\" at the end of a position (e.g., \"top1\") results in the legend being drawn horizontally instead of vertically.\n",
"#' @param args.legend List with arguments to pass to legend(). Defaults to list(bg = \"white\").\n",
"#' @param density Vector giving the density of shading lines, in lines per inch, for the bars or bar components. The default value of NULL means that no shading lines are drawn. Non-positive values of density also inhibit the drawing of shading lines.\n",
"#' @param angle Slope of shading lines, given as an angle in degrees (counter-clockwise), for the bars or bar components.\n",
"#' @param col Vector containing the color of bars. If NULL (default) colors are generated based on the rainbow-palette.\n",
"#' @param grid.col Character or rgb value containing the color of grid lines. Defaults to \"grey\".\n",
"#' @param axes Logical value indicating whether to plot axes. Defaults to T.\n",
"#' @param add Logical value indicating whether to plot the barplot to the current device. Defaults to F.\n",
"#' @param adj Numeric value between 0 and 1, indicating where to plot main title and axis labels - if any - between left (0) and right (1). Defaults to 0.5\n",
"#' @param default.labels Logical value, indicating whether to use traditional barplot-labels (which, e.g., hide in case of overlap) instead of bp-style labels. Defaults to F.\n",
"#' @param xlab Character value representing the label to be drawn next to the x-axis. Defaults to NA.\n",
"#' @param ylab Character value representing the label to be drawn next to the y-axis. Defaults to NA.\n",
"#' @param border Color of the bars' border. Defaults to NA.\n",
"#' @param grid.mode Numeric value specifying when to plot the grid. 0 for grid in the background, 1 for grid in the foreground. Defaults to 0.\n",
"#' @param ... Additional graphical parameters for barplot.\n",
"#' @details Plots a barplot and adds labels and numbers to bars. Optionally allows for plotting standard deviations around each bar.\n",
"#' @keywords plotting\n",
"#' @export\n",
"#' @examples\n",
"#' bp(data.frame(group1=c(variable1=1,variable2=2),group2=c(variable1=3,variable2=4)),horiz=T,main=\"Example\")"
);
f <- function (x = NULL, sd = NULL, cex = 1, beside = T, horiz = F, breakLabels = F,
add.numbers = F, ndigits = 2, ncex = NA, nsrt = 0, npos = NA,
ncol = "black", sdcol="grey", grid = T, plot = T, main = NULL, sub = NULL,
xlim.factor = 1.5, las = 1, srt = 45, xlim = NULL, ylim = NULL, names.arg = NULL,
legend.text = NULL, optimize.legend=T, args.legend = NULL, density = NULL,
angle = 45, col = NULL, grid.col = "grey", axes = T, add = F,
adj = 0.5, default.labels = F, xlab = NA, ylab = NA, border = NA,
grid.mode = 0, main1 = NULL, main2 = NULL, main3 = NULL,
adj.main1 = 0, adj.main2 = 0, adj.main3 = 0, col.main1 = "black",
col.main2 = "black", col.main3 = "black", cex.main1 = 1.2,
cex.main2 = 1.2, cex.main3 = 1.2, font.main1 = 1, font.main2 = 2,
font.main3 = 4, omitZeros = T, mar = NA, automar=F, ...)
{
addChars = ifelse(is.character(add.numbers), add.numbers, "")
mar0 = NULL
if (is.character(add.numbers)) add.numbers = T
if (is.null(ncex)) ncex = cex
else if (is.na(ncex)) ncex = cex
if (!is.null(npos))
if (is.na(npos))
if (beside == T)
npos = ifelse(horiz == T, 4, 3)
else npos = NULL
if (is.null(x)) x = data.frame(test1 = c(1, 2, 3), test2 = c(2, 3, 4))
else if (is.table(x)) {
y = matrix(sapply(x, as.numeric), nrow = dim(x)[1])
if (length(dim(x)) == 1) {
rownames(y) = names(x)
}
else {
rownames(y) = rownames(x)
colnames(y) = colnames(x)
}
x = y
}
el = list(...)
x = as.matrix(x)
if (is.character(x))
stop("Please provide numeric data!")
x2 = ifelse(dim(x)[2] == 1 & beside==T, list(x[, 1]), list(x))[[1]]
if (!is.null(sd)) {
sd = ifelse(dim(x)[2] == 1, list(as.matrix(sd)[, 1]), list(as.matrix(sd)))[[1]]
}
if (is.null(rownames(x)))
rownames(x) = 1:dim(x)[1]
if (is.null(colnames(x)))
colnames(x) = 1:dim(x)[2]
if (is.matrix(x2)) {
rownames(x2) = rownames(x)
colnames(x2) = colnames(x)
}
else names(x2) = rownames(x)
width = unlist(ifelse(length(el[["width"]]) > 0, el["width"], list(1))[[1]])
space = unlist(ifelse(length(el[["space"]]) > 0, el["space"], ifelse(beside & dim(x)[2] > 1, list(c(0, 1)), list(0.2)))[[1]])
if (is.null(col)) col = rainbow(dim(x)[1])
if (is.null(legend.text) & dim(x)[2] > 1) legend.text = rownames(x)
if(!is.null(legend.text))
if (sum(is.na(legend.text)) > 0) legend.text = NULL
else if (length(legend.text) == 1)
if (legend.text[[1]] == F) legend.text = NULL
if(length(args.legend)==1)
if(sum(is.na(args.legend))>0 | sum(args.legend==F)>0) legend.text = NULL
if (is.null(xlim))
if (!horiz) {
b = barplot(x2, beside = beside, horiz = horiz, plot = F, add = add, ...)
xlim = c(min(b) - (width[1]/2), max(b) + (width[1]/2))
if (!is.null(legend.text)) xlim[2] = xlim[2] * xlim.factor
}
else {
if (beside) { xlim = c(min(c(min(x), 0)), max(c(max(x), 0)))
} else { xlim = c(min(c(min(colSums(x)), 0)), max(c(max(colSums(x)), 0)))
}
if (!is.null(legend.text)) xlim[2] = xlim[2] * xlim.factor
}
if (is.null(ylim))
if (!horiz) {
if (beside) { ylim = c(min(c(min(x), 0)), max(c(max(x), 0)))
} else { ylim = c(min(c(min(colSums(x)), 0)), max(c(max(colSums(x)), 0)))
}
}
else {
b = barplot(x2, beside = beside, horiz = horiz, plot = F, add = add, ...)
ylim = c(min(b) - (width[1]/2), max(b) + (width[1]/2))
}
if (!is.null(names.arg)) {
if (length(names.arg) == 1)
if (is.na(names.arg))
names.arg = rep(NA, dim(x)[2])
if (dim(x)[2] == 1)
rownames(x) = names.arg
else colnames(x) = names.arg
}
else names.arg = ifelse(dim(x)[2] == 1, list(rownames(x)), list(colnames(x)))[[1]]
if (automar) mar=ifelse(horiz,list(qqBaseX::mar(labels2=names.arg)),list(qqBaseX::mar(labels1=names.arg)))[[1]]
if (is.numeric(mar)) {
mar0 = par("mar")
par(mar = mar)
}
b = NULL
if (grid.mode == 0) {
b = as.matrix(barplot(x2, beside = beside, horiz = horiz,
density = density, angle = angle, xlim = xlim, ylim = ylim, plot = plot,
las = las, add = add, adj = adj, main = main, sub = sub,
col = NA, xlab = xlab, ylab = ylab, border = NA, axes = F,
names.arg=ifelse(default.labels == T, list(names.arg), list(rep(NA, dim(x)[2])))[[1]], ...))
}
else {
b = as.matrix(barplot(x2, border = border, xlab = xlab,
ylab = ylab, names.arg = ifelse(default.labels == T, list(names.arg), list(rep(NA, dim(x)[2])))[[1]],
beside = beside, horiz = horiz, density = density,
angle = angle, col = col, xlim = xlim, ylim = ylim, main = main,
sub = sub, plot = plot, las = las, axes = F, add = add,
adj = adj, ...))
}
abline2 = function(xl, xlf, ...) {
xaxp <- ifelse((length(dev.list())>0|plot==T), list(par("xaxp")), list(c(0,1,5)))[[1]]
yaxp <- ifelse((length(dev.list())>0|plot==T), list(par("yaxp")), list(c(0,1,5)))[[1]]
segments(x0 = min(xl), y0 = seq(yaxp[1], yaxp[2], (yaxp[2] -
yaxp[1])/yaxp[3]), x1 = max(xl)/xlf, y1 = seq(yaxp[1],
yaxp[2], (yaxp[2] - yaxp[1])/yaxp[3]), ...)
}
abline3 = function(xl, xlf, ...) {
xaxp <- ifelse((length(dev.list())>0|plot==T), list(par("xaxp")), list(c(0,1,5)))[[1]]
yaxp <- ifelse((length(dev.list())>0|plot==T), list(par("yaxp")), list(c(0,1,5)))[[1]]
segments(y0 = min(xl), x0 = seq(xaxp[1], xaxp[2], (xaxp[2] -
xaxp[1])/xaxp[3]), y1 = max(xl)/xlf, x1 = seq(xaxp[1],
xaxp[2], (xaxp[2] - xaxp[1])/xaxp[3]), ...)
}
if (plot!=F)
if (!horiz) {
if (grid != F)
abline2(xlim, ifelse(!is.null(legend.text), xlim.factor, 1), col = grid.col)
}
else {
if (grid != F)
abline3(ifelse((length(dev.list())>0|plot==T), list(par("usr")), list(c(0,1,0,1)))[[1]][3:4], 1, col = grid.col)
}
if (grid.mode == 0 & plot != F)
b = as.matrix(barplot(x2, border = border, xlab = NA, ylab = NA, names.arg = rep(NA, dim(x)[2]),