-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstats.R
executable file
·1859 lines (1764 loc) · 58.1 KB
/
stats.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
#!/usr/bin/env Rscript
# rm(list=ls())
library(ggplot2);
library(ggpubr);
library(digest);
library(argparser);
library(cli);
library(utils);
library(stats);
library(openintro);
library(ggfortify);
library(PEIP);
library(corrplot);
library(ggiraphExtra);
#import the data from the file browser
# data <- read.csv(file.choose(),stringsAsFactors=FALSE);
# Welcome Message
welcomeMsg<-'Hi Welcome to the Stats Terminal by Aviv'
cli::cat_boxx(welcomeMsg)
# Topic 1
# Main Menu List //////
menuListT1<-c(
'Indicators (Location: Avg.,Median,Mode | Variability: Stdev,IQR,Range,CV)',
'Relationship',
'Histogram (Continous Data)',
'Histogram (Custom Data: No Percentage, Only Numeric Format)',
'Bar (Categorical Data)',
'Frequency Table',
'Frequency Table with Custom Breaks',
'Back'
);
# Main Menu Selection Function
topicI<-function(){
choice<-menu(menuListT1,title='What do you need?')
switch (choice,
'1' = {indicators();topicI()},
'2' = relationship(),
'3' = {histo();topicI()},
'4' = {histoCustom();topicI()},
'5' = {bar();topicI()},
'6' = {freqTableM();topicI()},
'7' = {CustomfreqTableM();topicI()},
'8' = topicSelect()
)
}
# Location Indicators Menu List
subMenu<-c(
'User Input',
'File',
'File Summary',
'Back'
)
# Location Indicators Selection Function
indicators<-function(){
choice<-menu(subMenu,title='Method? Remember the Col. Name is necessary in the CSV files)')
switch (choice,
'1' = {cat(indicatorsCal(toInt(inpSplit('Enter Values Separated by a Comma: ')),'user'));cat('\n')},
'2' = {cat(indicatorsCal(read.csv(file.choose(),stringsAsFactors=FALSE),'csv'));cat('\n')},
'3' = {cat(summary(read.csv(file.choose(),stringsAsFactors=FALSE)),sep='\n');cat('\n')},
'4' = topicI()
)
}
# Stats Basic Func.
indicatorsCal<-function(input,type){
if(identical(type,'user')){
u <- sd(input,na.rm = TRUE)
v <- max(input,na.rm = TRUE) - min(input,na.rm = TRUE)
m <- min(input,na.rm = TRUE)
mx <- max(input,na.rm = TRUE)
r <- IQR(input,na.rm = TRUE)
w <- mean(input, na.rm = TRUE)
x <- median(input, na.rm = TRUE)
y <- getmode(input)
cv <- u/w
z <- c('Mean:',w,'Median:',x,'Mode:',y,'Stdev:',u,'IQR:',r,'Range:',v,'Min:',m,'Max:',mx,'CV:',cv)
return(z);
}else{
u <- sd(unlist(input),na.rm = TRUE)
v <- max(unlist(input),na.rm = TRUE) - min(input,na.rm = TRUE)
m <- min(unlist(input),na.rm = TRUE)
mx <- max(unlist(input),na.rm = TRUE)
r <- IQR(unlist(input),na.rm = TRUE)
w <- mean(unlist(input),na.rm = TRUE)
x <- median(unlist(input),na.rm = TRUE)
y <- getmode(unlist(input))
cv <- u/w
z <- c('Mean:',w,'Median:',x,'Mode:',y,'Stdev:',u,'IQR:',r,'Range:',v,'Min:',m,'Max:',mx,'CV:',cv)
return (z)
}
}
# Relationship Menu List
subMenu1<-c(
'User Input',
'File',
'Back'
)
# Relationship Menu Selection Function
relationship<-function(){
choice<-menu(subMenu1,title='Method? Remember the Col. Name is necessary in the CSV files)')
switch (choice,
'1' = {cat(relationshipCal(toInt(inpSplit('2-Enter Values Separated by a Comma: ')),toInt(inpSplit('1-Enter Values Separated by a Comma: ')),'user'));cat('\n');relationship()},
'2' = {cat(relationshipCal(read.csv(file.choose(),stringsAsFactors=FALSE),'x','csv'));cat('\n');relationship()},
'3' = topicI()
)
}
# Relationship var. cal. func.
relationshipCal<-function(input,input1,type){
if(identical(type,'user')){
covar <- cov(input,input1)
correl <- cor(input,input1)
z <- c('Covariance:',covar,'Correlation:',correl)
return(z)
}else{
covar <- cov(input[,1],input[,2])
correl <- cor(input[,1],input[,2])
z <- c('Covariance:',covar,'Correlation:',correl)
return(z)
}
}
# Histogram Function
histo<-function(){
x <- read.csv(file.choose())
cn <-colnames(x)
un <- unlist(x)
hn<-hist(un, breaks = 'Sturges',plot = FALSE)
plot(hn,xlim=c(hn$breaks[1]-((hn$breaks[2]-hn$breaks[1]))*1.5,hn$breaks[length(hn$breaks)]+(hn$breaks[2]-hn$breaks[1])),ylim=c(0,max(hn$counts)+round(sum(hn$counts)/length(hn$counts))),xlab = cn,main = paste('Graph of',cn),col = 'blue',border='red',labels = TRUE)
h<-hist(un, breaks = 'Sturges',plot = FALSE)
h$density = h$counts/sum(h$counts)*100
plot(h,freq=FALSE, xlab = cn,ylab='RF',xlim=c(hn$breaks[1]-((hn$breaks[2]-hn$breaks[1]))*1.5,h$breaks[length(h$breaks)]+(hn$breaks[2]-hn$breaks[1])),ylim=c(0,max(h$density)+round(sum(h$density)/length(h$density))),main = paste('Graph of',cn,'percentage version'),col = 'red',border='blue',labels = TRUE)
}
histoCustom<-function(){
x <- read.csv(file.choose())
minVal<-as.vector(summary(x))[1]
cli_alert_warning(paste('Watch Out for the Minimum Value',minVal))
cn <-colnames(x)
un <- unlist(x)
info<-toInt(inpSplit('Enter Interval (Start,End,Step) in CSV: '))
br<-seq(info[1],info[2],by=info[3])
hn<-hist(un[un>info[1]&un<info[2]], breaks =br ,plot = FALSE)
plot(hn,xlim=c(hn$breaks[1]-((hn$breaks[2]-hn$breaks[1]))*1.5,hn$breaks[length(hn$breaks)]+(hn$breaks[2]-hn$breaks[1])),ylim=c(0,max(hn$counts)+round(sum(hn$counts)/length(hn$counts))),xlab = cn,main = paste('Graph of',cn),col = 'blue',border='red',labels = TRUE)
h<-hist(un[un>info[1]&un<info[2]], breaks = br,plot = FALSE)
h$density = h$counts/sum(h$counts)*100
plot(h,freq=FALSE, xlab = cn,ylab='RF',xlim=c(hn$breaks[1]-((hn$breaks[2]-hn$breaks[1]))*1.5,h$breaks[length(h$breaks)]+(hn$breaks[2]-hn$breaks[1])),ylim=c(0,max(h$density)+round(sum(h$density)/length(h$density))),main = paste('Graph of',cn,'percentage version'),col = 'red',border='blue',labels = TRUE)
}
# Barchart Function
bar<-function(){
x <- read.csv(file.choose())
df<-data.frame(x[!is.na(x)])
lvs <- levels(sort(unlist(x)))
count <- character()
for (variable in lvs) {
filter<-df[colnames(df)[1]]==variable
count<-c(count,length(df[filter,]))
}
xs <- data.frame('Levels'=lvs,'Count'=as.integer(count))
p <- ggplot(xs, aes(x=Levels, y=Count))+geom_bar(stat='identity')+
geom_text(aes(label=Count), vjust=-0.3, size=3.5)
print(p)
}
# FreqTable Menu List
subMenuF<-c(
'Right Open',
'Right Closed',
'Back'
)
# Frequency Table Selection Function
freqTableM<-function(){
choice<-menu(subMenuF,title='Method? Remember the Col. Name is necessary in the CSV files)')
switch (choice,
'1' = freqTable(FALSE),
'2' = freqTable(TRUE),
'3' = topicI()
)
}
# Frequency Table
freqTable<-function(openSide){
raw<-read.csv(file.choose())
summary(raw)
raw<-data.frame(raw[!is.na(raw)])
unlistraw<-unlist(raw)
hist <- hist(unlist(raw),breaks="Sturges", plot=FALSE,include.lowest=TRUE,right=openSide)
br=hist$breaks
cf = cbind(cumsum(table(cut(unlistraw,br,right=openSide))))
rf = cbind(table(cut(unlistraw,br,right=openSide)) /nrow(raw))
crf = cbind(cumsum(table(cut(unlistraw,br,right=openSide))))/nrow(raw)
df<-data.frame(bin=rownames(crf),AbsFreq_ni=hist$count, CumuFreq=cf, RelativeFreq_fi=rf, Cumu_RelativeFreq_Fi=crf)
rownames(df)<-NULL
print(df)
}
# Custom FreqTable Menu List
subMenuFC<-c(
'Right Open',
'Right Closed',
'Right Open (UpperLimitOnly)',
'Right Closed (UpperLimitOnly)',
'Back'
)
# Custom Frequency Table Selection Function
CustomfreqTableM<-function(){
choice<-menu(subMenuFC,title='Method? Remember the Col. Name is necessary in the CSV files)')
switch (choice,
'1' = CustomfreqTable(FALSE,TRUE), #(openSide,include.lowest)
'2' = CustomfreqTable(TRUE,TRUE),
'3' = CustomfreqTable(FALSE,FALSE),
'4' = CustomfreqTable(TRUE,FALSE),
'5' = topicI()
)
}
# Custom Frequency Table
CustomfreqTable<-function(openSide,lowest){
raw<-read.csv(file.choose())
minVal<-as.vector(summary(raw))[1]
cli_alert_warning(paste('Watch Out for the Minimum Value',minVal))
raw<-data.frame(raw[!is.na(raw)])
info<-toInt(inpSplit('Enter Interval (Start,End,Step) in CSV: '))
unlistraw<-unlist(raw)
unlistraw<-unlistraw[unlistraw>info[1]&unlistraw<info[2]]
br<-seq(info[1],info[2],by=info[3])
hist <- hist(unlistraw,breaks=br, plot=FALSE,include.lowest=lowest,right=openSide)
cf = cbind(cumsum(table(cut(unlistraw,br,right=openSide))))
rf = cbind(table(cut(unlistraw,br,right=openSide)) /nrow(raw))
crf = cbind(cumsum(table(cut(unlistraw,br,right=openSide))))/nrow(raw)
df<-data.frame(bin=rownames(crf),AbsFreq_ni=hist$count, CumuFreq=cf, RelativeFreq_fi=rf, Cumu_RelativeFreq_Fi=crf)
rownames(df)<-NULL
print(df)
}
# Topic II
menuListT2<-c(
'Probability Table',
'Back'
);
# Main Menu Selection Function
topicII<-function(){
choice<-menu(menuListT2,title='What do you need?')
switch (choice,
'1' = {probTable();topicII()},
'2' = topicSelect(),
)
}
probTable<-function(){
# Import the file
filex<-file.choose()
x<-read.csv(file=filex)
df<-data.frame(x)
# Row/col names
rownames(df)<-df[,1]
df[-c(1),-c(1)]
df<-df[,-1]
# Vertical Sum
verticalTotal<-numeric()
for (col in colnames(df)) {
verticalTotal<-c(verticalTotal,sum(df[col]))
}
# Update the df
df<-rbind(df,'Total'=verticalTotal)
# Horizontal Sum
horizontalTotal<-numeric()
for (rown in rownames(df)) {
horizontalTotal<-c(horizontalTotal,sum(df[rown,]))
}
# Update the df
df<-cbind(df,'Total'=horizontalTotal)
# Get the grand total
ro<-length(rownames(df))
co<-length(colnames(df))
grandSum<-df[ro,co]
# Calculate the percentage table
per<-data.frame(df/grandSum)
# The Table with the sum
cli_alert_info('Sum Table:')
print(df)
cat('\n')
# The percentage table
cli_alert_info('Percentage Table:')
print(per)
cat('\n')
# Conditional Probability
# cli_alert_info('Conditional Probability:')
condProb<-df[,!(colnames(per)=='Total')]
condProb<-per[!(rownames(per)=='Total'),]
# condProb<-condProb/per[,'Total']
# print(condProb)
# cat('\n')
# Degree of Freedom
degf<-(length(colnames(condProb))-1) * (length(rownames(condProb))-1)
# Remove the Total column
x<-per[length(rownames(per)),]
x[,length(colnames(x))]<-NULL
# Determin the event type
i<-0
filter<-character()
for (cols in x) {
i<-i+1
# filter<-c(filter,cols*per[,length(colnames(per))]==per[,i])
x<-cols*per[,length(colnames(per))]
y<-per[,i]
filter<-c(filter,as.double(x)==as.double(y))
}
roo<-length(rownames(per))
coo<-length(colnames(per))-1
eventTable<-matrix(filter,nrow=roo,ncol =coo)
cli_alert_info('Event Table: (True = Independent | False = Dependent)')
cli_alert_info('The Last Column will Always Equal True Because it is the Sum')
cli_alert_info('Note:If there are more than or equal to 2 trues then all is true regardless of the display')
print(eventTable)
# Barplot
barplotMenu<-c('True','False')
choice<-menu(barplotMenu,title='Bar Plot? ')
if(identical(choice,1L)){
condPM<-t(as.matrix(condProb))
bp<-barplot(condPM,ylab = 'Percentage',
ylim=c(0,max(condPM*3))
,legend=c(rownames(condPM))
,col=c("red","skyblue"),
args.legend=list(x='topright',bty="n",border=NA))
text(bp,condPM[2,]+condPM[1,],labels=paste(round(condPM[2,],5),'%'))
text(bp,condPM[2,],labels=paste(round(condPM[1,],5),'%'))
}
}
# Topic III
menuListT3<-c(
'Probability Table & Graph (No Percentage Format %) & Expected Val ...etc',
'Back'
);
# Main Menu Selection Function
topicIII<-function(){
choice<-menu(menuListT3,title='What do you need?')
switch (choice,
'1' = {discreteProbDistro();topicIII()},
'2' = topicSelect(),
)
}
discreteProbDistro<-function(){
# Import the file
filex<-file.choose()
x<-read.csv(file=filex,header = TRUE)
df<-data.frame(x)
# Get the total
total<-sum(df[,2])
# Calculate the percentage table
df<-cbind(df,data.frame('per.'=df[,2]/total))
print(df)
cat('\n')
# Expected val.
print('Expected Value: ')
expV<-crossprod(df[,1],df[,length(colnames(df))])[1]
print(expV)
cat('\n')
# Variance
print('Variance: ')
variance<-sum(((df[,1]-expV)^2)*df[,length(colnames(df))])
print(variance)
cat('\n')
# Stdev
print('Standard Deviation: ')
print(sqrt(variance))
# Plot
x=df[,1]
y=df[,2]
# Determine the breaks
hist<-hist(unlist(df),breaks = 'Sturges',plot=FALSE)$breaks
interval<-hist[length(hist)]-hist[length(hist)-1]
xmax<-interval+hist[length(hist)]
ymax<-max(df[length(colnames(df))])*2
# The plot object
plot(x,y,ylab='Probability',main=colnames(df)[1],type='h',col='blue',xlim = c(0,xmax),ylim=c(0,ymax))+
points(x,y,pch=16,cex=1,col="dark red")+text(x,y,labels=y,pos=3)
}
# Topic IV
menuListT4<-c(
'Normal Distribution Graph',
'Normal Distribution Calculation',
'Uniform Distribution Calculation',
'Standardized Distribution Calculation',
'Back'
);
# Main Menu Selection Function
topicIV<-function(){
choice<-menu(menuListT4,title='What do you need?')
switch (choice,
'1' = {normalDist();topicIV()},
'2' = {normalDistCal(FALSE);topicIV()},
'3' = {uniformDistCal();topicIV()},
'4' = {standardizeDistCal();topicIV()},
'5' = topicSelect(),
)
}
normalDist<-function(){
stdev<-toInt(readline(prompt='Enter the standard deviation: '))
avg<-toInt(readline(prompt='Enter the mean: '))
sample<-toInt(inpSplit('Enter Sample Info. (Start,End,Step) in CSV: '))
p<-ggdistribution(dnorm,seq(sample[1],sample[2],by=sample[3]),mean=avg,sd=stdev)
print(p)
}
normalDistCal<-function(sampling){
if(identical(sampling,TRUE)){
cli_alert_warning('The stdev of the sample and the stdev of the population is differet')
cli_alert_warning('However, the average will be the same')
}
type<-readline(prompt='P[X ≤ x] (default) or P[X > x] (>) or val2<x<val1 (bt) or prob->val (p): ')
if(identical(type,'>')){
if(identical(sampling,TRUE)){
info<-toInt(inpSplit('Enter (Value,Expected Value,Stderr) in CSV: '))
}else{
info<-toInt(inpSplit('Enter (Value,Mean,Stdev) in CSV: '))
}
p<-pnorm(info[1],info[2],info[3],lower.tail = FALSE)
print('The Probability is: ')
print(p)
cat('\n')
}else if(identical(type,'')){
if(identical(sampling,TRUE)){
info<-toInt(inpSplit('Enter (Value,Expected Value,Stderr) in CSV: '))
}else{
info<-toInt(inpSplit('Enter (Value,Mean,Stdev) in CSV: '))
}
p<-pnorm(info[1],info[2],info[3])
print('The Probability is: ')
print(p)
cat('\n')
}else if(identical(type,'p')){
if(identical(sampling,TRUE)){
info<-toInt(inpSplit('Enter (Prbability,Expected Value,Stderr) in CSV: '))
}else{
info<-toInt(inpSplit('Enter (Prbability,Mean,Stdev) in CSV: '))
}
val<-qnorm(info[1],info[2],info[3])
print('The Value is: ')
print(val)
cat('\n')
}else{
if(identical(sampling,TRUE)){
info<-toInt(inpSplit('Enter (Smaller Value, Larger Value,Expected Value,Stderr) in CSV: '))
}else{
info<-toInt(inpSplit('Enter (Smaller Value, Larger Value,Mean,Stdev) in CSV: '))
}
p1<-pnorm(info[1],info[3],info[4])
p2<-pnorm(info[2],info[3],info[4])
p3<-p2-p1
print('The Probability is: ')
print(p3)
cat('\n')
}
}
uniformDistCal<-function(){
type<-readline(prompt='P[X ≤ x] (default) or P[X > x] (>) or val2<x<val1 (bt) or prob->val (p): ')
if(identical(type,'>')){
info<-toInt(inpSplit('Enter (Value,Min,Max) in CSV: '))
p<-punif(info[1],info[2],info[3],lower.tail = FALSE)
print('The Probability is: ')
print(p)
cat('\n')
}else if(identical(type,'')){
info<-toInt(inpSplit('Enter (Value,Min,Max) in CSV: '))
p<-punif(info[1],info[2],info[3])
print('The Probability is: ')
print(p)
cat('\n')
}else if(identical(type,'p')){
info<-toInt(inpSplit('Enter (Prbability,Min,Max) in CSV: '))
val<-qunif(info[1],info[2],info[3])
print('The Value is: ')
print(val)
cat('\n')
}else{
info<-toInt(inpSplit('Enter (Smaller Value, Larger Value,Min,Max) in CSV: '))
p1<-punif(info[1],info[3],info[4])
p2<-punif(info[2],info[3],info[4])
p3<-p2-p1
print('The Probability is: ')
print(p3)
cat('\n')
}
}
standardizeDistCal<-function(){
type<-readline(prompt='P[X ≤ x] (default) or P[X > x] (>) or val2<x<val1 (bt) or prob->val (p): ')
if(identical(type,'>')){
info<-toInt(readline(prompt='Enter the Value: '))
p<-pnorm(info,lower.tail = FALSE)
print('The Probability is: ')
print(p)
cat('\n')
}else if(identical(type,'')){
info<-toInt(readline(prompt='Enter the Value: '))
p<-pnorm(info)
print('The Probability is: ')
print(p)
cat('\n')
}else if(identical(type,'p')){
info<-toInt(readline(prompt='Enter the Probability: '))
val<-qnorm(info)
print('The Value is: ')
print(val)
cat('\n')
}else{
info<-toInt(inpSplit('Enter (Smaller Value, Larger Value) in CSV: '))
p1<-pnorm(info[1])
p2<-pnorm(info[2])
p3<-p2-p1
print('The Probability is: ')
print(p3)
cat('\n')
}
}
# Topic V
menuListT5<-c(
'Standard Error Calculation (Numerical)',
'Standard Error Calculation (Categorical)',
'Sampling Distribution Calculation (Numerical)',
'Sampling Proportion Calculation (Categorical)',
'Back'
);
# Main Menu Selection Function
topicV<-function(){
cli_alert_info('Central Limit Theorem (CLT): ')
cli_alert_info('Sample Size > 30, the Sample = Normally Distributed')
cat('\n')
choice<-menu(menuListT5,title='What do you need?')
switch (choice,
'1' = {standardErrNumeric();topicV()},
'2' = {standardErrCategorical();topicV()},
'3' = {normalDistCal(TRUE);topicV()},
'4' = {normalDistCal(TRUE);topicV()},
'5' = topicSelect(),
)
}
standardErrNumeric<-function(){
popStdev<-toInt(readline(prompt='Enter the Population Stdev: '))
popSize<-toInt(readline(prompt='Enter the Population Size: '))
print(paste('Standard Error is',popStdev/sqrt(popSize)))
cat('\n')
}
standardErrCategorical<-function(){
cli_alert_info('Sampling Proportion: ')
cli_alert_info('Sample Size > 30 & Each Category >5')
cli_alert_info('The Sample = Normally Distributed')
expVal<-toInt(readline(prompt='Enter the Expected Value: '))
size<-toInt(readline(prompt='Enter the Sample Size: '))
print(paste('Standard Error (Categorical) is',sqrt(expVal*(1-expVal)/size) ))
cat('\n')
}
# Topic VI
menuListT6<-c(
'File: Confidence Interval Known Sigma: Normal Distribution (Numerical)',
'File: Confidence Interval Unknown Sigma: T Distribution (Numerical)',
'File: Confidence Interval Proportion (Categorical)',
'User: Confidence Interval Known Sigma: Normal Distribution (Numerical)',
'User: Confidence Interval Unknown Sigma: T Distribution (Numerical)',
'User: Confidence Interval Proportion (Categorical)',
'Back'
);
# Main Menu Selection Function
topicVI<-function(){
c# Welcome Message
warnMsg<-'Column Name Required for Calculation'
cli::cat_boxx(warnMsg)
choice<-menu(menuListT6,title='What do you need?')
switch (choice,
'1' = {confIntSigKnown();topicVI()},
'2' = {confIntSigUnKnown();topicVI()},
'3' = {confIntProportion();topicVI()},
'4' = {confIntSigKnownUser();topicVI()},
'5' = {confIntSigUnKnownUser();topicVI()},
'6' = {confIntProportionUser();topicVI()},
'7' = topicSelect(),
)
}
# Confidence Level with Known Sigma (stdev/sigma giving)
confIntSigKnown<-function(){
filex<-file.choose()
x<-read.csv(file=filex,header = TRUE)
df<-data.frame(x)
# Calculate the sample size and the average | get the sigma
sig<-toInt(readline(prompt='Enter the Sigma (Given Stdev): '))
sampleSize<-length(df[,1])
avg<-mean(df[,1])
# The confidence level
cl<-toInt(readline(prompt='Enter the Confidence Level (usually 95%): '))
sl<-1-cl
# The z value (the critical value)
z<-qnorm(cl+sl/2)
# The standard error
stderr<-sig/sqrt(sampleSize)
# Error margin
em<-stderr*z
# Precision
pres<-em/avg
# Lower Limit
ll<-avg-em
# Upper Limit
ul<-avg+em
#The result
cat('\n')
cli_alert_success('The Results:')
cat('\n')
result<-c(paste('Sigma:',sig),paste('Sample Size:',sampleSize)
,paste('Avg:',avg),paste('Confidence Level:',cl)
,paste('Significance Level:',sl),paste('Z-value:',z),
paste('Standard Error:',stderr),paste('Error Margin:',em),
paste('Precision:',pres),paste('Lower Limit:',ll),
paste('Upper Limit:',ul))
print(result)
cat('\n')
# Warning abt analysis
cli_alert_warning('The analysis should at least include the point of estimate (avg),')
cli_alert_warning('the margin of error, the confidence level, or the lower&upper limit')
cat('\n')
}
# Confidence Level with Unknown Sigma (using stdev from the sample)
confIntSigUnKnown<-function(){
filex<-file.choose()
x<-read.csv(file=filex,header = TRUE)
df<-data.frame(x)
# Calculate the sample size and the average | calculate the sigma
sig<-sd(df[,1])
sampleSize<-length(df[,1])
avg<-mean(df[,1])
# The confidence level
cl<-toInt(readline(prompt='Enter the Confidence Level (usually 95%): '))
sl<-1-cl
# The degree of freedom
degf<-sampleSize-1
# The t value (the critical value)
t<-tinv(cl+sl/2,degf)
# The standard error
stderr<-sig/sqrt(sampleSize)
# Error margin
em<-stderr*t
# Precision
pres<-em/avg
# Lower Limit
ll<-avg-em
# Upper Limit
ul<-avg+em
#The result
cat('\n')
cli_alert_success('The Results:')
cat('\n')
result<-c(paste('Sigma:',sig),paste('Sample Size:',sampleSize)
,paste('Avg:',avg),paste('Confidence Level:',cl)
,paste('Significance Level:',sl),paste('Degree of Freedom:',degf)
,paste('T-value:',t),paste('Standard Error:',stderr),paste('Error Margin:',em),
paste('Precision:',pres),paste('Lower Limit:',ll),paste('Upper Limit:',ul))
print(result)
cat('\n')
# Warning abt analysis
cli_alert_warning('The analysis should at least include the point of estimate (avg),')
cli_alert_warning('the margin of error, the confidence level, or the lower&upper limit')
cat('\n')
}
# Confidence Level with Proportion
confIntProportion<-function(){
cli_alert_warning('Remember T Distribution Does Not Apply to')
cli_alert_warning('Confidence Interval with Proportion ')
filex<-file.choose()
x<-read.csv(file=filex,header = TRUE)
df<-data.frame(x)
# Calculate the sample size
sampleSize<-length(df[,1])
# Get the proportion
pp<-toInt(readline(prompt='Enter the Proportion: '))
# The average p_bar
avg<- pp/sampleSize
# 1- p_bar
navg<-1-avg
# The confidence level
cl<-toInt(readline(prompt='Enter the Confidence Level (usually 95%): '))
sl<-1-cl
# The z value (the critical value)
z<-qnorm(cl+sl/2)
# The standard error
stderr<-sqrt(avg*navg/sampleSize)
# Error margin
em<-stderr*z
# Precision remains in percentage as all are in percentage already
pres<-em
# Lower Limit
ll<-avg-em
# Upper Limit
ul<-avg+em
#The result
cat('\n')
cli_alert_success('The Results:')
cat('\n')
result<-c(paste('Sample Size:',sampleSize),paste('Proportion:',pp)
,paste('Avg:',avg),paste('1-Avg:',navg),paste('Confidence Level:',cl)
,paste('Significance Level:',sl),paste('Z-value:',z)
,paste('Standard Error:',stderr),paste('Error Margin:',em),
paste('Precision:',pres),paste('Lower Limit:',ll),paste('Upper Limit:',ul))
print(result)
cat('\n')
# Warning abt analysis
cli_alert_warning('The analysis should at least include the point of estimate (avg),')
cli_alert_warning('the margin of error, the confidence level, or the lower&upper limit')
cat('\n')
}
# Confidence Level with Known Sigma (stdev/sigma giving) | User Input
confIntSigKnownUser<-function(){
# Calculate the sample size and the average | get the sigma
sig<-toInt(readline(prompt='Enter the Sigma (Given Stdev): '))
sampleSize<-toInt(readline(prompt='Enter the Sample Size: '))
# Population Average
avg<-toInt(readline(prompt='Enter the Population Average: '))
# The confidence level
cl<-toInt(readline(prompt='Enter the Confidence Level (usually 95%): '))
sl<-1-cl
# The z value (the critical value)
z<-qnorm(cl+sl/2)
# The standard error
stderr<-sig/sqrt(sampleSize)
# Error margin
em<-stderr*z
# Precision
pres<-em/avg
# Lower Limit
ll<-avg-em
# Upper Limit
ul<-avg+em
#The result
cat('\n')
cli_alert_success('The Results:')
cat('\n')
result<-c(paste('Sigma:',sig),paste('Sample Size:',sampleSize)
,paste('Avg:',avg),paste('Confidence Level:',cl)
,paste('Significance Level:',sl),paste('Z-value:',z),
paste('Standard Error:',stderr),paste('Error Margin:',em),
paste('Precision:',pres),paste('Lower Limit:',ll),
paste('Upper Limit:',ul))
print(result)
cat('\n')
# Warning abt analysis
cli_alert_warning('The analysis should at least include the point of estimate (avg),')
cli_alert_warning('the margin of error, the confidence level, or the lower&upper limit')
cat('\n')
}
# Confidence Level with Unknown Sigma (using stdev from the sample) | User Input
confIntSigUnKnownUser<-function(){
# Calculate the sample size and the average | calculate the sigma
sig<-toInt(readline(prompt='Enter the Sample Standard Deviation: '))
sampleSize<-toInt(readline(prompt='Enter the Sample Size: '))
avg<-toInt(readline(prompt='Enter the Sample Average: '))
# The confidence level
cl<-toInt(readline(prompt='Enter the Confidence Level (usually 95%): '))
sl<-1-cl
# The degree of freedom
degf<-sampleSize-1
# The t value (the critical value)
t<-tinv(cl+sl/2,degf)
# The standard error
stderr<-sig/sqrt(sampleSize)
# Error margin
em<-stderr*t
# Precision
pres<-em/avg
# Lower Limit
ll<-avg-em
# Upper Limit
ul<-avg+em
#The result
cat('\n')
cli_alert_success('The Results:')
cat('\n')
result<-c(paste('Sigma:',sig),paste('Sample Size:',sampleSize)
,paste('Avg:',avg),paste('Confidence Level:',cl)
,paste('Significance Level:',sl),paste('Degree of Freedom:',degf)
,paste('T-value:',t),paste('Standard Error:',stderr),paste('Error Margin:',em),
paste('Precision:',pres),paste('Lower Limit:',ll),paste('Upper Limit:',ul))
print(result)
cat('\n')
# Warning abt analysis
cli_alert_warning('The analysis should at least include the point of estimate (avg),')
cli_alert_warning('the margin of error, the confidence level, or the lower&upper limit')
cat('\n')
}
# Confidence Level with Proportion
confIntProportionUser<-function(){
cli_alert_warning('Remember T Distribution Does Not Apply to')
cli_alert_warning('Confidence Interval with Proportion ')
# Get the sample size
sampleSize<-pp<-toInt(readline(prompt='Enter the Sample Size: '))
# Get the proportion
pp<-toInt(readline(prompt='Enter the Proportion: '))
# The average p_bar
avg<- pp/sampleSize
# 1- p_bar
navg<-1-avg
# The confidence level
cl<-toInt(readline(prompt='Enter the Confidence Level (usually 95%): '))
sl<-1-cl
# The z value (the critical value)
z<-qnorm(cl+sl/2)
# The standard error
stderr<-sqrt(avg*navg/sampleSize)
# Error margin
em<-stderr*z
# Precision remains in percentage as all are in percentage already
pres<-em
# Lower Limit
ll<-avg-em
# Upper Limit
ul<-avg+em
#The result
cat('\n')
cli_alert_success('The Results:')
cat('\n')
result<-c(paste('Sample Size:',sampleSize),paste('Proportion:',pp)
,paste('Avg:',avg),paste('1-Avg:',navg),paste('Confidence Level:',cl)
,paste('Significance Level:',sl),paste('Z-value:',z)
,paste('Standard Error:',stderr),paste('Error Margin:',em),
paste('Precision:',pres),paste('Lower Limit:',ll),paste('Upper Limit:',ul))
print(result)
cat('\n')
# Warning abt analysis
cli_alert_warning('The analysis should at least include the point of estimate (avg),')
cli_alert_warning('the margin of error, the confidence level, or the lower&upper limit')
cat('\n')
}
# Topic VII
menuListT7<-c(
'Testing with Known Sigma: Normal Distribution (Numerical)',
'Testing with Unknown Sigma: T Distribution (Numerical)',
'Testing Proportion (Categorical)',
'Back'
);
# Main Menu Selection Function
topicVII<-function(){
choice<-menu(menuListT7,title='What do you need?')
switch (choice,
'1' = {testSigKnown();topicVII()},
'2' = {testSigUnKnown();topicVII()},
'3' = {testProportion();topicVII()},
'4' = topicSelect(),
)
}
testSigKnown<-function(){
# Step 0: Compute the sample size
sampleSize<-toInt(readline(prompt='Enter the Sample Size: '))
sampleAvg<-toInt(readline(prompt='Enter the Sample Average: '))
popStdev<-toInt(readline(prompt='Enter the Population Standard Deviation: '))
testVal<-toInt(readline(prompt='Enter the Value to be Tested: '))
# Step 1: Formulate the hypithesis
H1<-readline(prompt='H1-Enter Your Hypothesis: ')
H0<-readline(prompt='H0-Enter the Original Hypothesis: ')
# Step 2: Conditions of Validity
cli_alert_info('Sample size > 30 and known sigma(stdev): Normal Distro.')
cli_alert_info('Left Tail: H0-> P=P0 | H1-> P<P0')
cli_alert_info('Right Tail: H0-> P=P0 | H1-> P>P0')
cli_alert_info('Two Tail: H0-> P=P0 | H1-> P!=P0')
cat('\n')
# Test Menu
testType<-function(){
Test<-character()
testMenu<-c(
'Left Tail',
'Right Tail',
'Two Tail'
);
choice<-menu(testMenu,title='Select Test Type: ')
switch (choice,
'1' = Test<-'Left Tail',
'2' = Test<-'Right Tail',
'3' = Test<-'Two Tail'
)
}
testType<-testType()
# Step 3: Computation
stderr<-popStdev/sqrt(sampleSize)
# The test statistic (standardized)
z_cal<-(sampleAvg-testVal)/stderr
# Cumulative probability of z_cal
if(identical(testType,'Two Tail')){
p_val<-pnorm(z_cal)*2
}else if(identical(testType,'Right Tail')){
p_val<-pnorm(z_cal,lower.tail = FALSE)
}else if(identical(testType,'Left Tail')){
p_val<-pnorm(z_cal)
}
# The Significance Level (Alpha)
sl<-toInt(readline(prompt='Enter the Significance Level / Alpha (usually 5%): '))
# The critical value
if(identical(testType,'Two Tail')){
z_crit<-qnorm(1-sl/2)
}else if(identical(testType,'Right Tail')){
z_crit<-qnorm(sl,lower.tail = FALSE)
} else if(identical(testType,'Left Tail')){
z_crit<-qnorm(sl)
}
# General Info
ginfo<-c(paste('Sample Size:',sampleSize),paste('Average:',sampleAvg)
,paste('Population Stdev:',popStdev),paste('Test Value:',testVal),
paste('H0:',H0),paste('H1:',H1),paste('Test Type:',testType)
,paste('Standard Error:',stderr),paste('z_cal:',z_cal),
paste('p_val:',p_val),paste('Significance Level:',sl),paste('z_crit:',z_crit))
print(ginfo)
# Step 4: Decision
if(identical(testType,'Left Tail')){
if(z_cal>z_crit){
cli_alert_success(paste('Failure to Reject H0:',H0))
cli_alert_danger(paste('Reject H1:',H1))
}else if(z_cal<z_crit){
cli_alert_success(paste('Accept H1:',H1))
cli_alert_danger(paste('Reject H0:',H0))
}
}
if(identical(testType,'Right Tail')){
if(z_cal<z_crit){
cli_alert_success(paste('Failure to Reject H0:',H0))
cli_alert_danger(paste('Reject H1:',H1))
}else if(z_cal>z_crit){
cli_alert_success(paste('Accept H1:',H1))
cli_alert_danger(paste('Reject H0:',H0))
}
}
if(identical(testType,'Two Tail')){
if(abs(z_cal)<z_crit){
cli_alert_success(paste('Failure to Reject H0:',H0))
cli_alert_danger(paste('Reject H1:',H1))
}else if(abs(z_cal)>z_crit){
cli_alert_success(paste('Accept H1:',H1))
cli_alert_danger(paste('Reject H0:',H0))
}
}
}
testSigUnKnown<-function(){
# Step 0: Compute the sample size
sampleSize<-toInt(readline(prompt='Enter the Sample Size: '))
sampleAvg<-toInt(readline(prompt='Enter the Sample Average: '))
sampleStdev<-toInt(readline(prompt='Enter the Sample Standard Deviation: '))
testVal<-toInt(readline(prompt='Enter the Value to be Tested: '))
# Step 1: Formulate the hypithesis
H1<-readline(prompt='H1-Enter Your Hypothesis: ')
H0<-readline(prompt='H0-Enter the Original Hypothesis: ')
# Step 2: Conditions of Validity
cli_alert_info('Sample size > 30 and known sigma(stdev): Normal Distro.')
cli_alert_info('Left Tail: H0-> P=P0 | H1-> P<P0')
cli_alert_info('Right Tail: H0-> P=P0 | H1-> P>P0')
cli_alert_info('Two Tail: H0-> P=P0 | H1-> P!=P0')
cat('\n')