PichMixT commited on
Commit
c6a0031
·
verified ·
1 Parent(s): 8cceae1

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +165 -141
app.R CHANGED
@@ -1,141 +1,165 @@
1
- library(shiny)
2
- library(readr) # Untuk membaca file CSV
3
- library(readxl) # Untuk membaca file Excel (xlsx)
4
- library(haven) # Untuk membaca file SPSS (sav)
5
- library(expss)
6
- library(dplyr) # Untuk manipulasi data
7
- library(openxlsx) # Untuk menulis file xlsx
8
- library(DT) # Untuk tabel interaktif
9
-
10
- # Helper function for cross tabulation using cro_cpct() and cro_cases()
11
- create_crosstab <- function(data, row_vars, col_vars, use_percentage) {
12
- # Select the required columns for rows
13
- row_result <- data %>%
14
- select(all_of(row_vars)) %>%
15
- mutate(across(where(is.character), as.factor)) # Convert character to factor
16
-
17
- # Create a list with total() and the selected column variables
18
- column_result <- data %>%
19
- select(all_of(col_vars)) %>%
20
- mutate(across(where(is.character), as.factor)) # Convert character to factor
21
-
22
- # Pilih antara cro_cpct() atau cro_cases()
23
- if (use_percentage) {
24
- crosstab <- cro_cpct(row_result, list(total(),column_result))
25
- # Pembulatan 2 angka desimal
26
- #crosstab <- round(crosstab, 2)
27
- } else {
28
- crosstab <- cro_cases(row_result, list(total(),column_result))
29
- }
30
-
31
- return(crosstab)
32
- }
33
-
34
- # UI for the Shiny app
35
- ui <- fluidPage(
36
- titlePanel("Shiny App with Cross Tabulation"),
37
- sidebarLayout(
38
- sidebarPanel(
39
- # Upload file
40
- fileInput("file", "Upload CSV, Excel, or SPSS File",
41
- accept = c(".csv", ".xlsx", ".sav")),
42
-
43
- # Select column variables first, then row variables
44
- uiOutput("select_col_ui"),
45
- uiOutput("select_row_ui"),
46
-
47
- # Select whether to use percentages or actual numbers
48
- radioButtons("value_type", "Value Type",
49
- choices = list("Actual Numbers" = "actual",
50
- "Percentage" = "percentage"),
51
- selected = "actual"),
52
-
53
- # Submit button
54
- actionButton("submit", "Create Crosstab"),
55
-
56
- # Download button
57
- downloadButton("downloadData", "Download Crosstab")
58
- ),
59
- mainPanel(
60
- DTOutput("crosstab_table") # Output hasil crostab dengan DTOutput untuk tabel interaktif
61
- )
62
- )
63
- )
64
-
65
- # Server logic
66
- server <- function(input, output, session) {
67
-
68
- # Reactive value to store uploaded data
69
- data <- reactiveVal(NULL)
70
-
71
- observeEvent(input$file, {
72
- req(input$file)
73
-
74
- # Read the file based on its extension
75
- file_ext <- tools::file_ext(input$file$name)
76
-
77
- if (file_ext == "csv") {
78
- data(read_csv(input$file$datapath))
79
- } else if (file_ext == "xlsx") {
80
- data(read_excel(input$file$datapath))
81
- } else if (file_ext == "sav") {
82
- data(read_sav(input$file$datapath))
83
- } else {
84
- showNotification("Unsupported file format!", type = "error")
85
- }
86
- })
87
-
88
- output$select_col_ui <- renderUI({
89
- req(data())
90
- df <- data()
91
- # Column selection first
92
- selectInput("col_var", "Select Column Variables", choices = names(df), multiple = TRUE)
93
- })
94
-
95
- output$select_row_ui <- renderUI({
96
- req(input$col_var) # Ensure column is selected first
97
- df <- data()
98
- # Row selection after column
99
- selectInput("row_var", "Select Row Variables", choices = names(df), multiple = TRUE)
100
- })
101
-
102
- crosstab <- reactive({
103
- req(input$submit)
104
- req(data())
105
- df <- data()
106
- row_vars <- input$row_var
107
- col_vars <- input$col_var
108
- use_percentage <- input$value_type == "percentage"
109
-
110
- # Make sure the selected columns exist in the data
111
- if (length(row_vars) == 0 || length(col_vars) == 0) {
112
- showNotification("Please select at least one row and one column variable", type = "error")
113
- return(NULL)
114
- }
115
-
116
- # Generate the crosstab
117
- create_crosstab(df, row_vars, col_vars, use_percentage)
118
- })
119
-
120
- # Output crosstab as a DataTable
121
- output$crosstab_table <- renderDT({
122
- result <- crosstab()
123
- req(result)
124
- datatable(result, options = list(pageLength = 10, autoWidth = TRUE))
125
- })
126
-
127
- output$downloadData <- downloadHandler(
128
- filename = function() {
129
- paste("crosstabulation-", Sys.Date(), ".xlsx", sep="")
130
- },
131
- content = function(file) {
132
- wb <- createWorkbook()
133
- sh1 = addWorksheet(wb, "Crosstab")
134
- xl_write(crosstab(),wb, sh1)
135
- saveWorkbook(wb, file, overwrite = TRUE)
136
- }
137
- )
138
- }
139
-
140
- # Create the Shiny app
141
- shinyApp(ui = ui, server = server)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ library(shiny)
2
+ library(DT)
3
+ library(readxl)
4
+ library(haven)
5
+ library(openxlsx)
6
+ library(expss)
7
+ library(dplyr)
8
+
9
+ ui <- fluidPage(
10
+ titlePanel("Shiny App: Cross Tabulation"),
11
+
12
+ sidebarLayout(
13
+ sidebarPanel(
14
+ fileInput("file", "Upload File (CSV, XLSX, SAV)", accept = c(".csv", ".xlsx", ".sav")),
15
+
16
+ # Input for R script
17
+ textAreaInput(
18
+ "r_script",
19
+ label = "Write R Script to Modify Data:",
20
+ #value = "data$New_Column <- data$Score * 2", # Example default script
21
+ rows = 10,
22
+ placeholder = "Write R code here to modify the dataframe, example: data$New_Column <- data$Score * 2"
23
+ ),
24
+ actionButton("apply_script", "Apply Script"),
25
+ br(),
26
+
27
+ # Select the data source for the crosstab
28
+ selectInput("data_source", "Select Data Source for Crosstab",
29
+ choices = c("Original Data" = "original", "Modified Data" = "modified")),
30
+
31
+ # Crosstab selections
32
+ selectInput("col_vars", "Select Column Variables", choices = NULL, multiple = TRUE),
33
+ selectInput("row_vars", "Select Row Variables", choices = NULL, multiple = TRUE),
34
+ selectInput("crosstab_type", "Crosstab Type",
35
+ choices = c("Absolute Values", "Percentage", "Mean Score")),
36
+ actionButton("generate_crosstab", "Generate Crosstab"),
37
+
38
+ # Download Crosstab
39
+ downloadButton("download_crosstab", "Download Crosstab")
40
+ ),
41
+
42
+ mainPanel(
43
+ tabsetPanel(
44
+ tabPanel("Original Data", DTOutput("original_data_table")),
45
+ tabPanel("Modified Data", DTOutput("modified_data_table")),
46
+ tabPanel("Crosstab Output", DTOutput("crosstab_table"))
47
+ )
48
+ )
49
+ )
50
+ )
51
+
52
+ server <- function(input, output, session) {
53
+ # Reactive values for data
54
+ original_data <- reactiveVal(NULL)
55
+ modified_data <- reactiveVal(NULL)
56
+
57
+ # Load original data
58
+ observeEvent(input$file, {
59
+ req(input$file)
60
+
61
+ file_ext <- tools::file_ext(input$file$name)
62
+ if (file_ext == "csv") {
63
+ df <- read.csv(input$file$datapath)
64
+ } else if (file_ext == "xlsx") {
65
+ df <- read_excel(input$file$datapath)
66
+ } else if (file_ext == "sav") {
67
+ df <- haven::read_sav(input$file$datapath)
68
+ for (var in names(df)) {
69
+ var_lab(df[[var]]) <- var_lab(df[[var]]) # Keep variable labels
70
+ }
71
+ } else {
72
+ showNotification("Unsupported file format!", type = "error")
73
+ return()
74
+ }
75
+
76
+ original_data(df)
77
+
78
+ # Display the original data in the Original Data tab
79
+ output$original_data_table <- renderDT({
80
+ datatable(original_data(), options = list(pageLength = 10, scrollX = TRUE))
81
+ })
82
+
83
+ # Update dropdown variabel
84
+ updateSelectInput(session, "col_vars", choices = names(df))
85
+ updateSelectInput(session, "row_vars", choices = names(df))
86
+
87
+ showNotification("Original data loaded successfully!", type = "message")
88
+ })
89
+
90
+ # Apply R script to modify data
91
+ observeEvent(input$apply_script, {
92
+ req(input$r_script)
93
+ req(original_data()) # Pastikan data asli sudah dimuat
94
+
95
+ tryCatch({
96
+ # Ambil data asli
97
+ df <- original_data()
98
+
99
+ # Evaluasi skrip di lingkungan khusus
100
+ env <- new.env()
101
+ env$data <- df # Data asli disimpan dalam lingkungan evaluasi
102
+
103
+ eval(parse(text = input$r_script), envir = env) # Evaluasi skrip
104
+
105
+ # Ambil hasil modifikasi dari lingkungan
106
+ modified_data(env$data)
107
+
108
+ # Tampilkan data hasil modifikasi di tab Modified Data
109
+ output$modified_data_table <- renderDT({
110
+ datatable(modified_data(), options = list(pageLength = 10, scrollX = TRUE))
111
+ })
112
+
113
+ showNotification("Script applied successfully!", type = "message")
114
+ }, error = function(e) {
115
+ showNotification(paste("Error in script:", e$message), type = "error")
116
+ })
117
+ })
118
+
119
+
120
+ # Generate Crosstab
121
+ crosstab <- eventReactive(input$generate_crosstab, {
122
+ req(input$col_vars, input$row_vars)
123
+
124
+ # Pilih data berdasarkan sumber yang dipilih
125
+ df <- if (input$data_source == "original") {
126
+ original_data()
127
+ } else {
128
+ modified_data()
129
+ }
130
+
131
+ # Prepare row and column variables
132
+ row_result <- df %>% select(all_of(input$row_vars))
133
+ column_result <- df %>% select(all_of(input$col_vars))
134
+
135
+ # Crosstab calculation based on type
136
+ if (input$crosstab_type == "Absolute Values") {
137
+ cro_cases(row_result, list(total(), column_result))
138
+ } else if (input$crosstab_type == "Percentage") {
139
+ cro_cpct(row_result, list(total(), column_result))
140
+ } else {
141
+ cro_mean_sd_n(row_result, list(total(), column_result))
142
+ }
143
+ })
144
+
145
+ # Render Crosstab
146
+ output$crosstab_table <- renderDT({
147
+ req(crosstab())
148
+ datatable(crosstab(), options = list(pageLength = 10, scrollX = TRUE))
149
+ })
150
+
151
+ # Download Crosstab
152
+ output$download_crosstab <- downloadHandler(
153
+ filename = function() {
154
+ paste("crosstab-", Sys.Date(), ".xlsx", sep = "")
155
+ },
156
+ content = function(file) {
157
+ wb <- createWorkbook()
158
+ sh1 <- addWorksheet(wb, "Crosstab")
159
+ xl_write(crosstab(), wb, sh1)
160
+ saveWorkbook(wb, file, overwrite = TRUE)
161
+ }
162
+ )
163
+ }
164
+
165
+ shinyApp(ui, server)