Reputation: 31
I am trying to load multiple files and merge using Reduce function... Tried with several options but got same error Got 'xtable' applied to an object of class "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"))
)
))
Upvotes: 1
Views: 1675
Reputation: 31
List the data frame --
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]])))
})
})
Upvotes: 0
Reputation: 330353
You simply reduce a wrong thing. Assuming you have only two files 'file1.csv', 'file2.csv' but it should work with larger number of files as well:
> 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
You can use either Reduce
:
> Reduce(merge, dfs)
x y z
1 1 4 9
2 2 5 10
or even better simple do.call
:
> do.call(merge, dfs)
x y z
1 1 4 9
2 2 5 10
If you want to translate it to your app you can use something like this:
Reduce(
merge, lapply(
paste('file', 1:input$fnos),
function(x) read.csv(input[[x]]$datapath)
))
Just remember about checking if input is set.
Upvotes: 1