首页 > 解决方案 > 如何在源文件“SplitColumn.R”中使用 R 中的“splitColumn”按钮

问题描述

在 R Shiny 中,以下代码“app.R”将 CSV 文件作为用户的输入文件,并在主面板中填充数据表。有时该表已合并列“类型”,我想使用下面的函数对其进行拆分。我想在 R 中保留一个按钮“SplitColumn”,它应该做同样的事情。

我想在 R Shiny 应用程序中使用“splitColumn.R”作为源文件,这样当用户上传 csv 文件时,他们可以选择列名并按下“SplitColumn”按钮以获取结果。

因为我是 Shiny 的新手,所以我无法在服务器级别将操作按钮 (SplitColumn) 与“splitColumn.R”连接起来。

我希望在这里得到一些帮助。

CSV 数据包含:

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

应用程序.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)
}

标签: rshiny

解决方案


你可以把你的代码splitColumn.R放在一个函数中。

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
}

app.R用于在observeEvent点击时调用函数。

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)

推荐阅读