UseMethod出错(“xtable”)

时间:2015-06-18 16:51:37

标签: r shiny

我正在尝试加载多个文件并使用Reduce函数进行合并... 尝试了几个选项,但得到了同样的错误 得到'xtable'应用于“character”类的对象

server.R

library(shiny)

shinyServer(function(input,output) {
    output$data <- renderUI({
        res <- lapply(
            1:input$fnos,
            function(i) {
                fileInput(paste("file", i),
                "Load File",
                accept=c(
                    'text/csv',
                    'text/comma-separated-values',
                    'text/tab-separated-values',
                    'text/plain','.csv','.tsv' ))}
        )
        do.call(sidebarPanel,res)   
    })

    output$multi <- renderTable({
        infile <- list(
            lapply(1:input$fnos, function(i) {input[[paste("file",i)]]})
        )[[1]]

        # for data frame names
        df <- (LETTERS[1:input$fnos])

        # trying to use assign function to create
        # different dataframes using read.csv
        for (i in 1:input$fnos) {assign(df[i], read.csv(infile[[c(i,4)]]))}

        #merging using Reduce function
        merged <- Reduce(function(x,y) merge(x,y), list(df))
        # getting error here
    }) 
})

ui.R

library(shiny)

shinyUI(fluidPage(
    titlePanel(title="Multiple File Load"),
    sidebarLayout(
        sidebarPanel(
            numericInput("fnos","Files input",1)),
        mainPanel(uiOutput("data"), tableOutput("multi"))
    )
))

2 个答案:

答案 0 :(得分:1)

你只是减少了一个错误的东西。假设您只有两个文件'file1.csv','file2.csv',但它也可以使用大量文件:

> write.csv(structure(list(id = 1:3, x = 4:6), .Names = c("x", "y"), class = "data.frame", row.names = c(NA, -3L)), 'file1.csv', row.names=FALSE)
> write.csv(structure(list(id = 1:2, y = 9:10), .Names = c("x", "z"), class = "data.frame", row.names = c(NA, -2L)), 'file2.csv', row.names=FALSE)
> dfs <- lapply(list.files(pattern="file[1-2]\\.csv$"), read.csv)
> dfs
[[1]]
  x y
1 1 4
2 2 5
3 3 6

[[2]]
  x  z
1 1  9
2 2 10

您可以使用Reduce

> Reduce(merge, dfs)
  x y  z
1 1 4  9
2 2 5 10

甚至更简单的do.call

> do.call(merge, dfs)
  x y  z
1 1 4  9
2 2 5 10

如果您想将其翻译成您的应用,可以使用以下内容:

Reduce(
    merge, lapply(
        paste('file', 1:input$fnos),
        function(x) read.csv(input[[x]]$datapath)
))

请记住检查是否设置了输入。

答案 1 :(得分:0)

列出数据框 -

library(shiny)
shinyServer(function(input,output)
{
  output$data <- 
    renderUI({
      res <- lapply(1:input$fnos, function(i) {fileInput(paste("file",i),"Load File",accept =c('text/csv',
              'text/comma-separated-values',
              'text/tab-separated-values',
              'text/plain','.csv','.tsv' ))})
      do.call(sidebarPanel,res)   
    })

  output$multi <- renderTable({
    infile <- list(lapply(1:input$fnos, function(i) {input[[paste("file",i)]]}))[[1]]
    mm = list()
    for (i in 1:input$fnos) 
      {
        mm[[i]] <- read.csv(infile[[c(i,4)]])
      }
    merged <- Reduce(merge, lapply(1:input$fnos, function(i) list(mm[[i]])))
  }) 
})