forked from cardiomoon/r-sem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.R
executable file
·2663 lines (2198 loc) · 78.9 KB
/
server.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(shiny)
#require(moonBook)
#require(ztable)
#require(mycor)
#require(ggplot2)
require(plyr)
require(rmarkdown)
require(readxl)
#require(ggthemes)
#require(reshape)
#require(shinyjs)
require(flextable)
require(lavaan)
require(semPlot)
require(semTools)
require(extrafont)
#require(matrixpls)
require(semMediation)
require(ggplot2)
#require(shinyDND)
require(stringr)
require(mycor)
require(dplyr)
require(moonBook)
require(rrtable)
require(DT)
require(webrSub)
#require(shinyTree)
source("cleaning.R")
# source("chooser.R")
#loadfonts()
myexample=read.csv("example.csv")
myequation=myexample$myequation
myfile=myexample$myfile
mymethod=myexample$method
set.seed(1234)
example1 <- data.frame(y = rnorm(100),
x1 = rnorm(100),
x2 = rnorm(100),
x3 = rnorm(100))
set.seed(1234)
X <- rnorm(100)
M <- 0.5*X + rnorm(100)
Y <- 0.7*M + rnorm(100)
example2 <- data.frame(X , Y , M )
#ADHD=read.csv("data/ADHD.csv")
childhood=read.csv("childhood.csv")
load("translation.bin") # contains the dictionary, parsed as a double list
options(ztable.type="html")
options(shiny.maxRequestSize=30*1024^2)
dic=read.csv("dictionary.csv",fileEncoding="utf-8",stringsAsFactors = FALSE)
help_console <- function(topic, format=c("text", "html", "latex", "Rd"),
lines=NULL, before=NULL, after=NULL) {
format=match.arg(format)
if (!is.character(topic)) topic <- deparse(substitute(topic))
helpfile = utils:::.getHelpFile(help(topic))
hs <- capture.output(switch(format,
text=tools:::Rd2txt(helpfile),
html=tools:::Rd2HTML(helpfile),
latex=tools:::Rd2latex(helpfile),
Rd=tools:::prepare_Rd(helpfile)
)
)
if(!is.null(lines)) hs <- hs[lines]
hs <- c(before, hs, after)
cat(hs, sep="\n")
invisible(hs)
}
shinyServer(function(input, output,session) {
shinyjs::onclick("toggleModelPlot", shinyjs::toggle(id = "modelPlot", anim = TRUE))
shinyjs::onclick("toggleFinalPlot", shinyjs::toggle(id = "finalPlot", anim = TRUE))
shinyjs::onclick("toggle2ndEquation", shinyjs::toggle(id = "2ndEquation", anim = TRUE))
shinyjs::onclick("toggleHelpOp", shinyjs::toggle(id = "helpOperator", anim = TRUE))
shinyjs::onclick("toggleHelpData", shinyjs::toggle(id = "helpData", anim = TRUE))
tr <- function(text){ # translates text into current language
sapply(text,function(s) translation[[s]][[input$language]], USE.NAMES=FALSE)
}
tr2out=function(string,size=3){
output[[string]]=renderPrint(cath(tr(string),size))
}
md2html=function(string){
HTML(markdownToHTML(fragment.only=TRUE,text=string))
}
file2ext=function(filename){
namelist=unlist(strsplit(filename,".",fixed=TRUE))
result=namelist[length(namelist)]
result=tolower(result)
if((result=="csv")|(result=="xlsx")|(result=="rds")) return(result)
else return(NULL)
}
file2newname=function(file){
mypath=unlist(strsplit(file$datapath,"/"))
length(mypath)
temp=mypath[1]
for(i in 2:(length(mypath)-1)) temp=paste(temp,mypath[i],sep="/")
result=paste(temp,"/","test.",file2ext(file$name),sep="")
result
}
my_theme=function(p){
if(input$theme!="gray") {p<-eval(parse(text=paste("p+theme_",input$theme,"()",sep="")))}
p
}
my_readfile=function(file){
ext=file2ext(file$name)
result=NULL
if(is.null(ext)) {
session$sendCustomMessage(type = 'testmessage',
message = list( 'Only file with xlsx or csv or RDS format is supported.'))
} else if(ext=="csv") {
try(result<-read.csv(file$datapath,header=TRUE,stringsAsFactors = FALSE),silent=TRUE)
if(is.null(result)) {
try(result<-read.csv(file$datapath,header=TRUE,fileEncoding="euc-kr",stringsAsFactors = FALSE),silent=TRUE)
if(is.null(result)) session$sendCustomMessage(type = 'testmessage',
message = list( 'File read error : please check file encoding'))
}
} else if(ext=="rds"){
result=readRDS(file$datapath)
result=data.frame(result)
} else{
newname=file2newname(file)
file.copy(file$datapath,newname)
result=read_excel(newname)
if(is.null(result)) session$sendCustomMessage(type = 'testmessage',
message = list( 'File read error : please check file encoding'))
}
result
}
mypaste=function(tempA,...,sep=","){
result=""
if(tempA=="") result=paste0(...)
else result=paste0(tempA,sep,...)
result
}
myplotPNG=function(listf,width=input$plotWidth,height=input$plotHeight,
units="in",res=300,start=0){
filename=c()
count=length(listf)
if(count>0) for(i in 1:count){
path <- paste("plot_", i+start, ".png", sep="")
filename <- c(filename, path)
plotPNG(listf[[i]],path,width=width,height=height,
units=units,res=res)
}
filename
}
myplotPDF=function(listf,isggplot=NULL,width=input$plotWidth,height=input$plotHeight,
units="in",res=300,start=0){
filename=c()
count=length(listf)
if(is.null(isggplot)) isggplot=rep(FALSE,count)
if(count>0) for(i in 1:count){
path <- paste("plot_", i+start, ".pdf", sep="")
filename <- c(filename, path)
plotPDF(listf[[i]],path,width=width,height=height,
units=units,res=res,isggplot[i])
}
filename
}
plotPDF=function(fun,file,width=7,height=5,units="in",res=300,ggplot=FALSE){
if(ggplot) ggsave(file,fun(),width=width,device=cairo_pdf,height=height,units=units,dpi=res)
else {
cairo_pdf(file,width=width,height=height)
#pdf(file,paper="letter")
fun()
dev.off()
}
}
myplotSVG=function(listf,isggplot=NULL,width=input$plotWidth,height=input$plotHeight,
start=0){
filename=c()
count=length(listf)
if(is.null(isggplot)) isggplot=rep(FALSE,count)
if(count>0) for(i in 1:count){
path <- paste("plot_", i+start, ".svg", sep="")
filename <- c(filename, path)
plotSVG(listf[[i]],path,width=width,height=height,
isggplot[i])
}
filename
}
plotSVG=function(fun,file,width=7,height=5,ggplot=FALSE){
if(ggplot) ggsave(file,fun(),width=width,height=height)
else {
svg(file,width=width,height=height)
#pdf(file,paper="letter")
fun()
dev.off()
}
}
cath=function(string="",size=3){
cat(paste("<h",size,">",string,"</h",size,">",sep=""))
}
sectionReport2=function(reportname){
downloadHandler(
filename = function() {
paste(reportname, sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
#if(input$format=="PDF") tempname=paste(reportname,'1.Rmd',sep="")
#else
tempname=paste(reportname,'.Rmd',sep="")
src <- normalizePath(tempname)
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, tempname)
out <- render(tempname, switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
output$semReport=sectionReport2("semReport")
putmsg=function(msg="test message"){
session$sendCustomMessage(type = 'testmessage',message = list( msg))
}
values=reactiveValues()
current<-""
currentdir=getwd()
tempdir=tempdir()
owd <- setwd(tempdir)
on.exit(setwd(owd))
setwd(currentdir)
setHot=function(x) values[["Hot"]]=x
observeEvent(input$Example,{
if(input$Example=="uploaded_file") updateTextInput(session,"mydata",value="uploaded")
else updateTextInput(session,"mydata",value=input$Example)
})
origin=reactive({
if(input$mydata=="uploaded") {
if(is.null(input$file)) {
if(input$language=="en") putmsg("Please upload file first !")
else putmsg("먼저 file을 업로드하세요 !")
df<-HolzingerSwineford1939
updateRadioButtons(session,"Example",
selected="HolzingerSwineford1939")
updateTextInput(session,"mydata",
value="HolzingerSwineford1939")
}
else df<-my_readfile(input$file)
}
else {
is.csv=grep(".csv",input$mydata)
if(length(is.csv)==0) df=eval(parse(text=input$mydata))
else df<-read.csv(paste("data/",input$mydata,sep=""),stringsAsFactors = FALSE)
}
values$choice=input$mydata
values$new<-TRUE
df
})
observe({
updateSelectInput(session,"base_family",choices=c("Helvetica","NanumGothic",fonts()))
})
output$x1<-DT::renderDT(df(),editable=TRUE)
proxy = dataTableProxy('x1')
observeEvent(input$x1_cell_edit, {
x<-df()
info = input$x1_cell_edit
str(info)
i = info$row
j = info$col
v = info$value
x[i, j] <- DT::coerceValue(v, x[i, j])
replaceData(proxy, x, resetPaging = FALSE)
if(input$mydata=="edited"){
edited1<<-x
updateTextInput(session,"mydata",value="edited1")
} else{
edited<<-x
updateTextInput(session,"mydata",value="edited")
}
})
df=reactive({
origin()
})
observe({
df=df()
vars=c("Select..."="",colnames(df))
# For Meta-analysis
updateSelectInput(session,"leftvar",choices=c(vars,"indirect effect","total effect"))
updateSelectInput(session,"rightvar",choices=c(vars,"1"))
updateSelectInput(session,"indepvar",choices=vars)
updateSelectInput(session,"resvar",choices=vars)
updateSelectInput(session,"mediator",choices=vars)
updateSelectInput(session,"group",choices=c("",vars))
if(input$language=="kor") {
shinyjs::html("Title1","<h1>웹에서 하는 R 구조 방정식 모형</h1>")
shinyjs::html("editOrder","<strong>분석 명령어 편집</strong>")
shinyjs::html("summaryOptions","<strong>요약 옵션 선택</strong>")
shinyjs::html("otherOptions","<strong>기타 옵션 선택</strong>")
shinyjs::html("order1","<strong>R 분석명령어 편집</strong>")
shinyjs::html("order2","<strong>R 분석명령어 편집-두번째 모형</strong>")
shinyjs::html("doSEM"," 분 석 하 기 ")
shinyjs::html("ResetEx","예제초기화")
shinyjs::html("showHelpData","데이타 도움말 보기")
shinyjs::html("exportCSV","데이터 CSV로 저장")
shinyjs::html("add","구조방정식에 추가")
shinyjs::html("reset","구조방정식 초기화")
shinyjs::html("semReport","보고서 다운로드")
shinyjs::html("downloadPlot","플롯 다운로드")
shinyjs::html("downloadPPT","파워포인트로 다운로드")
shinyjs::html("helpOp","? 연산자")
shinyjs::html("toggleFinalPlot","<h4>플롯 옵션 보기/가리기</h4>")
shinyjs::html("toggleHelpOp","연산자 도움말" )
shinyjs::html("toggleHelpData","데이터 도움말 보기/가리기")
shinyjs::html("introduction",md2html(
"이 앱을 사용하여 `구조방정식 모형`을 이용한 분석을 할 수 있습니다. `확인요인분석`,`구조방정식 모형`,
`교차타당성분석`,`매개효과분석`,`부분최소회귀모형(PLS)`를 사용한 분석 등을 시행할 수 있습니다.
분석과 함께 멋진 plot을 얻을 수 있으며 plot 을 고해상도 이미지(png)로 저장하거나 벡터그래픽(svg) 또는 pdf 형식으로
다운로드 할 수 있으며 `파워포인트` 파일로도 다운로드 받을 수 있습니다. 자료가 준비된 경우 자료의 분석과 파워포인트 파일
다운로드까지 일분이면 충분합니다."))
updateSelectInput(session, "SelectEx",label="예제 선택",
choices=c("선택안함"=0,"확인요인분석"=1,
"구조방정식모형"=2,"교차타당성분석"=3,
"매개효과분석"=4,
"ADHD 데이타"=6,
"childhood"=7))
updateRadioButtons(session, "method",label = "분석 옵션 선택",
choices=c("구조방정식모형 사용"="sem",
"확인분석모형 사용"="cfa",
"부분최소회귀(PLS)모형 사용"="matrixpls"))
updateRadioButtons(session, inputId = "Example", label = "데이타 선택",
choices = c("HolzingerSwineford1939",
"PoliticalDemocracy",
"example1",
"example2",
"ADHD",
"childhood",
"업로드한 파일"="uploaded_file"),selected=input$Example)
}
else {
shinyjs::html("Title1","<h1>Structural Equation Modeling with R</h1>")
shinyjs::html("editOrder","<strong>Edit Anlysis Order</strong>")
shinyjs::html("summaryOptions","<strong>Summary Options</strong>")
shinyjs::html("otherOptions","<strong>Other Options</strong>")
shinyjs::html("order1","<strong>Edit the Analysis Order</strong>")
shinyjs::html("order2","<strong>Edit the Analysis Order - The 2nd Equation</strong>")
shinyjs::html("doSEM","do Anlaysis")
shinyjs::html("ResetEx","Reset Example")
shinyjs::html("showHelpData","show help Data")
shinyjs::html("exportCSV","Export to CSV")
shinyjs::html("add","add to equation")
shinyjs::html("reset","reset the equation")
shinyjs::html("semReport","download Report")
shinyjs::html("downloadPlot","download Plot(s)")
shinyjs::html("downloadPPT","download pptx")
shinyjs::html("helpOp","? operator")
shinyjs::html("toggleFinalPlot","<h4>Plot Options show/hide</h4>")
shinyjs::html("toggleHelpOp","?Operator" )
shinyjs::html("toggleHelpData","Help for Data show/hide")
shinyjs::html("introduction",md2html(
"With this app, you can perform `structural equation modeling` with `just one-click`.
You can perform the `confirmatory factor analysis`, fit a `structural equation model`,
and fit a `partial least square(PLS) model`.
Additionally, you can obtain beautiful plots in png, svg or pdf format.
You can download the results with html or PDF format.
You can also download the powerpoint file with `just one click`."))
updateSelectInput(session,inputId = "SelectEx",label="Select Example",
choices=c("None"=0,"Confirmatory Factor Analysis"=1,
"Structural Equation Model"=2,
"Cross-Validation Analysis"=3,
"Mediation Effect Analysis"=4,
"ADHD data"=6))
updateRadioButtons(session,"method",label="Analysis options",
choices=c("fit a Structural Equation Model"="sem",
"fit a Confirmatory Factor Analysis Models"="cfa",
"fit a Partial Least Squares Model"="matrixpls"))
updateRadioButtons(session,inputId = "Example", label = "Select Data",
choices = c( "HolzingerSwineford1939",
"PoliticalDemocracy",
"example1",
"example2",
"ADHD",
"uploaded_file"),selected=input$Example)
}
headings=dic$key[dic$class=="output"]
for(i in 2:length(headings)) tr2out(headings[i])
checks=dic$key[dic$class=="Checkbox"]
for(i in 1:length(checks)) updateCheckboxInput(session,checks[i],label=tr(checks[i]))
selects=dic$key[dic$class=="Select"]
for(i in 1:length(selects)) updateSelectInput(session,selects[i],label=tr(selects[i]))
texts=dic$key[dic$class=="Text"]
for(i in 1:length(texts)) updateTextInput(session,texts[i],label=tr(texts[i]))
radios=dic$key[dic$class=="Radio"]
for(i in 1:length(radios)) updateRadioButtons(session,radios[i],label=tr(radios[i]))
numerics=dic$key[dic$class=="Numeric"]
for(i in 1:length(numerics)) updateNumericInput(session,numerics[i],label=tr(numerics[i]))
updateRadioButtons(session,'language',label=tr('language'))
})
observe({
if(input$editAnalysis) updateTextInput(session,"AnalysisOrder",value=myfittext())
#shinyjs::toggleState(id='semReport',condition=TRUE==FALSE)
#shinyjs::toggleState(id='downloadPlot',condition=TRUE==FALSE)
#shinyjs::toggleState(id='downloadPPT',condition=TRUE==FALSE)
})
observe({
if(input$SelectEx!=0){
choice=as.integer(input$SelectEx)
updateRadioButtons(session,"Example",
selected=myfile[choice])
updateTextInput(session,"equation",value=myequation[choice])
updateRadioButtons(session,"method",selected=mymethod[choice])
vars=colnames(origin())
if(choice==3) updateSelectInput(session,"group",choices=c("",vars),selected="school")
else updateSelectInput(session,"group",selected="")
}
})
plustext=function(x){
if(is.null(x)) result=""
if(length(x)>0) result=x[1]
if(length(x)>1) for(i in 2:length(x)) result=paste(result,x[i],sep="+")
result
}
annotatetext=function(x){
if(is.null(x)) result=""
else{
if(length(x)>0) result=paste0("c('",x[1],"'")
if(length(x)>1) {
for(i in 2:length(x)) result=paste0(result,",'",x[i],"'")
}
result=paste0(result,")")
}
result
}
EqText=reactive({
temp=""
if(input$lefttext!="") temp=input$lefttext
else temp=plustext(input$leftvar)
if((temp=="") & (length(input$rightvar)==0)) result<-""
else{
result=paste(temp,input$operator, plustext(input$rightvar))
}
result
})
observeEvent(input$add, {
if(input$equation=="") updateTextInput(session,"equation",value=EqText())
else updateTextInput(session,"equation",value=paste(input$equation,EqText(),sep="\n"))
})
extractLatentVar=function(){
newvar=c()
if(input$equation!=""){
equations=unlist(strsplit(input$equation,"\n",fixed=TRUE))
for(i in 1:length(equations)){
if(grepl("=~",equations[i])==TRUE) {
temp=unlist(strsplit(equations[i],"=~",fixed=TRUE))[1]
newvar=c(newvar,temp)
}
}
}
newvar
}
observeEvent(input$equation,{
newvar=c()
if(input$equation!="") newvar=extractLatentVar()
#cat("\nnewvar=",newvar)
newchoices=c("Select..."="",colnames(df()),newvar)
#cat("\nnewchoices=",newchoices)
updateSelectInput(session,"leftvar",choices=newchoices,selected="")
updateSelectInput(session,"rightvar",choices=newchoices,selected="")
updateSelectInput(session,"indepvar",choices=newchoices)
updateSelectInput(session,"resvar",choices=newchoices)
updateSelectInput(session,"mediator",choices=newchoices)
updateSelectInput(session,"group",choices=newchoices)
updateTextInput(session,"lefttext",value="")
})
# output$Drag=renderUI({
# newvar=extractLatentVar()
# newchoices=c(colnames(df()),newvar)
# tagList(
# p("Available variables"),
# dragSetUI("vars",textval=as.list(newchoices)))
#
#
# })
#
# output$Drop=renderUI({
# tagList(
# p("Independent variables"),
# dropUI("XVars",class = "dropelement",row_n=3,col_n=3),
# p("Mediators"),
# dropUI("MVars",class = "dropelement",row_n=3,col_n=3),
# p("Dependent variables"),
# dropUI("YVars",class = "dropelement",row_n=3,col_n=3),
# p("Discards"),
# dropUI("Discards",row_n=5,col_n=3)
# #,actionButton("ResetDND","Reset")
# )
# })
#
# observeEvent(input$ResetDND,{
# cat("\nResetDND")
# input$XVars=""
# input$MVars=""
# input$YVars=""
# })
#
newchoices=reactive({
df=df()
newvar=extractLatentVar()
newchoices=c(colnames(df),newvar)
temp="structure(list("
for(i in 1:length(newchoices)){
if(i>1) temp=paste0(temp,",")
temp=paste0(temp,newchoices[i],"=''")
}
temp=paste0(temp,"),stopened=TRUE)")
#cat("temp=",temp)
result=eval(parse(text=temp))
result
})
# output$tree <- renderTree({
#
# list(
# allVars=newchoices(),
# independentVars = structure("",stopened=TRUE),
# mediators=structure("",stopened=TRUE),
# dependentVars=structure("",stopened=TRUE)
#
#
# )
#
# })
# output$treestr <- renderPrint({
#
# # shinyTrees will also be available as inputs so you can
# # monitor changes that occur to the tree as the user interacts
# # with it.
# str(input$tree)
#
# cat("independentVars=")
# str(names(input$tree$independentVars))
# cat("\nmediators=")
# str(names(input$tree$mediators))
# cat("dependentVars=")
# str(names(input$tree$dependentVars))
# })
#
observeEvent(input$addMediationEquation, {
updateTextInput(session,"equation",value=paste0(input$equation,"\n",input$mediationEquation))
})
makeMediatorEq=function(){
temp=""
if(length(input$indepvar)*length(input$resvar)*length(input$mediator)==0) temp=""
else {
temp=makeEquation(X=input$indepvar,M=input$mediator,Y=input$resvar)
}
temp
}
observeEvent(input$MakeEquation, {
temp<-makeMediatorEq()
if(temp=="") putmsg("Please Select Variables First")
else {
updateTextInput(session,"mediationEquation",value=temp)
}
})
# observeEvent(input$addMediationEquation2, {
# updateTextInput(session,"equation",value=paste0(input$equation,input$mediationEquation2))
# })
# drop2str=function(x){
# # cat("\nx=")
# # str(x)
# res=unlist(strsplit(str_trim(x),"\n",fixed=TRUE))
# res=str_trim(res)
# res=res[nchar(res)>0]
# # cat("\nres=")
# #str(res)
# res
# }
#
# makeMediatorEq2=function(){
# temp=""
# if(length(input$XVars)*length(input$MVars)*length(input$YVars)==0) temp=""
# else {
# xvar=drop2str(input$XVars)
# mvar=drop2str(input$MVars)
# yvar=drop2str(input$YVars)
#
# temp=makeEquation(X=xvar,M=mvar,Y=yvar)
# }
# temp
# }
#
# observeEvent(input$MakeEquation2, {
#
# temp<-makeMediatorEq2()
# if(temp=="") putmsg("Please Select Variables First")
# else {
# updateTextInput(session,"mediationEquation2",value=temp)
#
# }
#
# })
#
observeEvent(input$reset, {
updateTextInput(session,"equation",value="")
updateSelectInput(session,"leftvar",selected="")
updateSelectInput(session,"rightvar",selected="")
})
observeEvent(input$resetMediation, {
updateTextInput(session,"mediationEquation",value="")
updateSelectInput(session,"indepvar",selected="")
updateSelectInput(session,"mediator",selected="")
updateSelectInput(session,"resvar",selected="")
})
# observeEvent(input$resetMediation2, {
# updateTextInput(session,"mediationEquation2",value="")
#
# })
#
observeEvent(input$ResetEx, {
updateTextInput(session,"equation",value="")
updateSelectInput(session,"SelectEx",selected=0)
updateSelectInput(session,"group",selected="")
updateRadioButtons(session,"method",selected="sem")
updateCheckboxInput(session,"fit.measures",value=FALSE)
})
output$EquationText=renderPrint({
if(EqText()=="") {
if(input$language=="en") cat("Select variables and operators to make a equation !")
else cat("변수와 연산자를 선택하여 구조방정식을 만드세요!")
}
else cat(EqText())
})
output$exportCSV = downloadHandler(
filename="Mydata.csv",
content=function(file){
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
write.csv(df(),file=file,row.names=FALSE)
},
contentType="text/csv"
)
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('report.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report.Rmd')
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
# })
# change character variables to factor variables
df1=reactive({
df1=df()
select=sapply(df1,function(x) length(unique(x))<=4)
count=length(which(select==TRUE))
if(count>1) df1[,select]=lapply(df1[,select],factor)
else if(count==1) df1[select]=lapply(df1[select],factor)
df1
})
output$dataHelp<-renderUI({
# if(input$Example=="ADHD"){
# # cath("Data Set fo Teacher's Intervention fo ADHD")
# # cath("id: study identification number",5)
# # cath("gender: male=1, female=2",5)
# # cath("age: age groups 1-4",5)
#
# includeMarkdown("ADHD.md")
#
# } else
htmlOutput("dataHelpHTML")
})
output$operatorHelp<-renderUI({
column(6,wellPanel(
if(input$language=="kor") includeMarkdown("operatork.md")
else includeMarkdown("operator.md")
))
})
output$dataHelpHTML=renderPrint({
if(input$Example=="example1") {
cath("Sample Data Made By the Following Code")
cath("set.seed(1234)",5)
cath("y=rnorm(100)",5)
cath("x1=rnrom(100)",5)
cath("x2=rnrom(100)",5)
cath("x3=rnrom(100)",5)
cath("example1=data.frame(y,x1,x2,x3)",5)
} else if(input$Example=="example2"){
cath("Sample Data Made By the Following Code")
cath("set.seed(1234)",5)
cath("X <- rnorm(100)",5)
cath("M <- 0.5*X + rnorm(100)",5)
cath("Y <- 0.7*M + rnorm(100)",5)
cath("example2 <- data.frame(X , Y , M )",5)
} else help_console(input$Example,"html")
})
output$Howto1=renderUI({
includeMarkdown("Howto1.md")
# if(input$language=="en") includeMarkdown("Howto1.md")
# else includeMarkdown("Howto1k.md")
})
output$Howto2=renderUI({
includeMarkdown("Howto2.md")
# if(input$language=="en") includeMarkdown("Howto2.md")
# else includeMarkdown("Howto2k.md")
})
output$Howto3=renderUI({
includeMarkdown("Howto3.md")
# if(input$language=="en") includeMarkdown("Howto3.md")
# else includeMarkdown("Howto3k.md")
})
output$Howto4=renderUI({
includeMarkdown("Howto4.md")
# if(input$language=="en") includeMarkdown("Howto4.md")
# else includeMarkdown("Howto4k.md")
})
output$Howto5=renderUI({
includeMarkdown("Howto5.md")
# if(input$language=="en") includeMarkdown("Howto5.md")
# else includeMarkdown("Howto5k.md")
})
output$Howto6=renderUI({
includeMarkdown("Howto6.md")
# if(input$language=="en") includeMarkdown("Howto6.md")
# else includeMarkdown("Howto6k.md")
})
output$Howto7=renderUI({
includeMarkdown("Howto7.md")
})
output$Howto8=renderUI({
includeMarkdown("Howto8.md")
})
output$about=renderUI({
if(input$language=="en") includeMarkdown("aboute.md")
else includeMarkdown("about.md")
})
output$citation1=renderPrint({
if(input$language=="kor"){
cat(paste("먼저 방법에서 ",version$version.string,"을 사용하여 통계처리를 하였다.`라고 기술해야 한다. 패키지를 사용하는 경우 패키지를 인용해야 하는데 대부분의 경우 통계분석을 하는데 사용한 모든 R패키지를 다 인용하지는 않는다. 일반적으로 사용되는 통계방법이 아닌 새로운 통계방법이나 통계방법을 특별히 언급해야 할 필요가 있는 경우에만 인용하는 것이 일반적이다. R version 은 달라질 수 있다. R version 및 사용한 패키지 정보는 다음 version() 및 sessionInfo()에서 확인할 수 있다.\n",sep=""))
cat("\n\nR의 version\n\n")
print(version)
cat("\n\n웹 R의 sessionInfo()\n\n")
print(sessionInfo())
cat("\nReferences\n\n")
cat("1. R을 인용할 때:\n")
print(citation())
cat("2. lavaan 패키지의 인용정보\n")
print(citation("lavaan"))
cat("3. semPlot 패키지의 인용정보\n")
print(citation("semPlot"))
} else{
cat(paste("In your 'Method' section, please citate R as 'Analyses were performed using ",version$version.string," statistical software.' You can find informations about R version and sessionInfo as followings.\n",sep=""))
cat("\n\nR version\n\n")
print(version)
cat("\n\nsessionInfo() of r-meta.com\n\n")
print(sessionInfo())
cat("\nReferences\n\n")
cat("1. To citate R:\n")
print(citation())
cat("2. To citate package 'lavaan'\n")
print(citation("lavaan"))
cat("3. To citate package 'semPlot'\n")
print(citation("semPlot"))
}
})
output$sem.ui1=renderUI({
input$doSEM
isolate({
if(input$equation!=""){
#fit<-myfit()
tagList(
# htmlOutput('result0'),
# verbatimTextOutput('semPlotText0'),
# plotOutput('SEMPlot0',height=700),
#
# if(input$equation2!="") verbatimTextOutput('semPlotText02'),
# if(input$equation2!="") plotOutput('SEMPlot02',height=700),
htmlOutput('result2'),
verbatimTextOutput('semText'),
htmlOutput('result1'),
verbatimTextOutput('semPlotText'),
uiOutput('semplot.ui'),
#plotOutput('SEMPlot',height=700),
if(input$equation2!="") verbatimTextOutput('semPlotText2'),
if(input$equation2!="") uiOutput('semplot2.ui')
#plotOutput('SEMPlot2',height=700)
)
}
})
})
output$semplot.ui=renderUI({
input$doSEM
isolate({
if(input$equation!=""){
if(input$group=="") plotOutput('SEMPlot',height=700)
else {
count=length(unique(df()[[input$group]]))
if(count==1) plotOutput('SEMPlot',height=700)
else {
fit<-myfit()
diagram<-mysemPlot(DoNotPlot=TRUE)
semplot_output_list<-lapply(1:count,function(i) {
semplotname<-paste0("semplot",i)
diagram[[i]]$Arguments$DoNotPlot=FALSE
output[[semplotname]] <- renderPlot({
qgraph::qgraph(diagram[[i]])
title(paste0(input$group,"=",i))
})
plotOutput(semplotname,height=700)
})
do.call(tagList,semplot_output_list)
}
}
}
})
})
output$semplot2.ui=renderUI({
input$doSEM
isolate({
if(input$equation2!=""){