Reputation: 314
in R Shiny, The below code "app.R" takes a CSV file as an input file from the user and populates the data table in the main panel. sometimes the table has merged columns "Type" which I want to split using the function below. I would like to keep a button "SplitColumn" in R shiny that should do the same.
I'd want to utilize "splitColumn.R" as a source file in the R shiny app, so that when a user uploads a csv file, they can select the column name and push the "SplitColumn" button to get the results.
Because I'm new to Shiny, I'm having trouble connecting the action button (SplitColumn) with "splitColumn.R" at the server level.
I'm hoping for some assistance here.
CSV data contains:
before_merge<- data.frame(ID=21:23, Type=c('A1 B1', 'C1 D1', 'E1 F1'))
splitColumn.R
library(dplyr)
library(tidyr)
library(stringr)
library(tidyverse)
library(stringr)
library(svDialogs)
column_name <- dlg_input("Enter a number", Sys.info()["user"])$res
before_merge<- data.frame(ID=21:23, Type=c('A1 B1', 'C1 D1', 'E1 F1'))
before_merge
library(reshape2)
newColNames <- c("Unmerged_type1", "Unmerged_type2")
#column_name <- readline(prompt="Enter the desired column name: ")
newCols <- colsplit(before_merge[[column_name]], " ", newColNames)
after_merge <- cbind(before_merge, newCols)
after_merge[[column_name]] <- NULL
app.R
## Only run examples in interactive R sessions
if (interactive()) {
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
actionButton("Splitcolumn", "SplitColumn"),
),
mainPanel(
tableOutput("contents")
)
)
)
server <- function(input, output) {
output$contents <- renderTable({
file <- input$file1
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
read.csv(file$datapath, header = input$header)
})
}
shinyApp(ui, server)
}
Upvotes: 2
Views: 68
Reputation: 389047
You can put your code of splitColumn.R
in a function.
splitColumn <- function(data, column_name) {
newColNames <- c("Unmerged_type1", "Unmerged_type2")
newCols <- colsplit(data[[column_name]], " ", newColNames)
after_merge <- cbind(data, newCols)
after_merge[[column_name]] <- NULL
after_merge
}
In app.R
use observeEvent
to call the function on click.
library(shiny)
source('SplitColumn.R')
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
actionButton("Splitcolumn", "SplitColumn"),
),
mainPanel(
tableOutput("contents")
)
)
)
server <- function(input, output) {
rv <- reactiveValues(data = NULL)
observe({
file <- input$file1
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
rv$data <- read.csv(file$datapath, header = input$header)
})
output$contents <- renderTable({
req(rv$data)
rv$data
})
observeEvent(input$Splitcolumn, {
rv$data <- splitColumn(rv$data, 'Type')
})
}
shinyApp(ui, server)
Upvotes: 0