The code below is written in R shiny and currently reads data from the 'mtcars' database. This app was made to replace the specific data in a column., It has options such as 'Column to search' for selecting columns, "replace" and "By" for replacing values that the user specifies in the 'Replace' field. It is now working perfectly.
But what I really want is to use 'Browse' to upload my own csv data and perform the same operations as 'Replace' and 'BY'. How to accomplish this?
Expected result:
How can values be replaced? (from old to new values). as an example How should I modify the value 100 to 500 in the 'range' column by referencing the column name in the 'select column' from the below csv data?
current csv:
ID Type Category Range
21 A1 B1 100
22 C1 D1 200
23 E1 F1 300
Expected CSV results:
ID Type Category Range
21 A1 B1 500
22 C1 D1 200
23 E1 F1 300
app.R
library(shiny)
library(DT)
library(dplyr)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept = ".csv"),
selectInput("col", "Column to search:", names(mtcars), names(mtcars)[1]),
textInput("old", "Replace:"),
textInput("new", "By:"),
actionButton("replace", "Replace!"),
),
mainPanel(
DTOutput("table1")
)
)
)
server <- function(input, output, session) {
my_data <- reactiveVal(mtcars)
observeEvent(input$replace, {
req(input$col)
dat <- my_data()
traf <- if (is.numeric(dat[[input$col]])) as.numeric else identity
my_data(dat %>%
mutate(!!rlang::sym(input$col) :=
replace(!!rlang::sym(input$col),
as.character(!!rlang::sym(input$col)) == input$old,
input$new) %>%
traf()))
})
output$table1 <- renderDT(
my_data()
)
}
shinyApp(ui, server)
CodePudding user response:
You just need to add the fileUploader
logic to fill my_data
accordingly:
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
selectInput("col", "Column to search:", NULL),
textInput("old", "Replace:"),
textInput("new", "By:"),
actionButton("replace", "Replace!"),
),
mainPanel(
DTOutput("table1")
)
)
)
server <- function(input, output, session) {
my_data <- reactiveVal(NULL)
observeEvent(input$file1, {
file <- input$file1
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
my_data(read.csv(file$datapath, header = input$header))
updateSelectInput(session, "col", choices = names(my_data()))
})
observeEvent(input$replace, {
req(input$col)
dat <- req(my_data())
traf <- if (is.numeric(dat[[input$col]])) as.numeric else identity
my_data(dat %>%
mutate(!!rlang::sym(input$col) :=
replace(!!rlang::sym(input$col),
as.character(!!rlang::sym(input$col)) == input$old,
input$new) %>%
traf()))
})
output$table1 <- renderDT(
req(my_data())
)
}