使用R Shiny上传后编辑数据框

3

我建立了一个闪亮的应用程序,它可以接受用户上传的CSV文件并为其添加表头和一些新列,以便之后进行一些计算。

上传的CSV文件包含2列,如下所示:

1  0.21
1  0.20
1  0.23
2  0.40
2  0.42
2 ...

我使用以下代码上传文件(该代码已经工作):

data1<- reactive({
    inFile <- input$file1
    if(is.null(inFile)){return()}
    data1<- read.csv(file=inFile$datapath,header =input$header,sep=input$sep)
})

下一步是将标题添加到这两列,并以以下方式添加另外两列:
Dose  Response SquareRoot    Log  
1     0.21     sq(Response)  log(Response)
1     0.20     ...           ...
1     0.23     ...           ...
2     0.40     ...           ...
2     0.42     ...           ...
2 ...

在R会话中,我要使用的代码是这样的:
  data1<- read.csv(file=inFile$datapath,header =input$header,sep=input$sep)
  colnames(data1) <-c("Dose","Response")
  data1$ResponseLog <- log10(data1$Response + 1)
  data1$ResponseSqRoot <- sqrt(data1$Response + 1)

如果我在Rshiny应用程序中添加这些行,它不起作用并给出错误:ERROR:argument of length 0,即使我只是使用colnames()定义列名。
所以我的问题是,有没有办法编辑我刚上传的数据框?如果已经有人问过这个问题,你能否将我重定向到那里,因为我找不到解决方案。希望我提供的细节足够让你理解这个问题。

1
看看这个问题 - 我认为它可能会有所帮助 https://dev59.com/O3nZa4cB1Zd3GeqPrY2W - John Paul
所以,首先我使用reactiveFileReader()上传文件,然后创建一个新对象,使我能够修改数据框。我是对的吗? - Daniele Avancini
基本上是的,您需要使用正确的列名创建数据框。然后,您可以通过响应式方式将上传的数据添加到这些列中。接下来,您可以进行任何计算等操作。 - John Paul
1个回答

7
希望这能帮到你:我还添加了一个按钮。
rm(list = ls())
library(shiny)

ui = fluidPage(
    sidebarPanel(
      fileInput('file1', 'Choose file to upload',accept = c('text/csv','text/comma-separated-values','text/tab-separated-values','text/plain','.csv','.tsv')),
      checkboxInput('header', 'Header', TRUE),
      radioButtons('sep', 'Separator',c(Comma=',',Semicolon=';',Tab='\t'),'Comma'),
      radioButtons('quote', 'Quote',c(None='','Double Quote'='"','Single Quote'="'"),'Double Quote'),
      actionButton("Load", "Load the File"),width = 3),
    mainPanel(tableOutput("my_output_data"))
)

server = function(input, output) {

  data1 <- reactive({
    if(input$Load == 0){return()}
    inFile <- input$file1
    if (is.null(inFile)){return(NULL)}

    isolate({ 
    input$Load
    my_data <- read.csv(inFile$datapath, header = input$header,sep = input$sep, quote = input$quote,stringsAsFactors =FALSE)
    colnames(my_data) <-c("Dose","Response")
    my_data$ResponseLog <- log10(my_data$Response + 1)
    my_data$ResponseSqRoot <- sqrt(my_data$Response + 1)
    })
    my_data
  })
  output$my_output_data <- renderTable({data1()},include.rownames=FALSE)  

}
runApp(list(ui = ui, server = server))

非常感谢您,老爸。那完美地解决了问题。 - Daniele Avancini
很高兴能够帮忙,请仔细阅读Shiny主页上的教程。 - Pork Chop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接