本文介绍了在R SHINY中读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我正在用R shiny构建一个应用程序,它要求用户上传一个.csv文件。一旦被R SHINY读入,我不确定如何实际操作要使用的对象。一般代码语法如下:
UI文件:
#ui.R
# Define UI for random distribution application
shinyUI(fluidPage(
# Application title
titlePanel("ORR Simulator"),
# Sidebar with controls to select the random distribution type
# and number of observations to generate. Note the use of the
# br() element to introduce extra vertical spacing
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Select the XXX.csv file',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
fileInput('file2', 'Select the YYY.csv file',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
numericInput("S", "Number of simulations to run:", 100),
mainPanel(
plotOutput("plot")
)
)
))
服务器文件:
#server.R
library(shiny)
shinyServer(function(input, output) {
text1 <- renderText({input$file1})
text2 <- renderText({input$file2})
file1 = read.csv(text1)
file2 = read.csv(text2)
output$plot <- renderPlot({
plot(file1[,1],file2[,2])
})
})
所以我本以为text1和text2会保存包含文件路径的字符串,但事实似乎并非如此。最终,我只希望能够读入两个数据集,并从那里能够基于这两个数据集对输出进行分析。
当然,使用renderText也可能是错误的想法,所以我们非常感谢任何关于如何做得更好的建议。
推荐答案
这里有一个很好的示例http://shiny.rstudio.com/gallery/file-upload.html。但为了完整起见,我将工作答案包含在下面。关键是您应该使用file$datapath
引用文件,并检查输入是否为空(当用户尚未上传文件时)。
server.R
#server.R
library(shiny)
shinyServer(function(input, output) {
observe({
file1 = input$file1
file2 = input$file2
if (is.null(file1) || is.null(file2)) {
return(NULL)
}
data1 = read.csv(file1$datapath)
data2 = read.csv(file2$datapath)
output$plot <- renderPlot({
plot(data1[,1],data2[,2])
})
})
})
ui.R
library(shiny)
#ui.R
# Define UI for random distribution application
shinyUI(fluidPage(
# Application title
titlePanel("ORR Simulator"),
# Sidebar with controls to select the random distribution type
# and number of observations to generate. Note the use of the
# br() element to introduce extra vertical spacing
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Select the XXX.csv file',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
fileInput('file2', 'Select the YYY.csv file',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
numericInput("S", "Number of simulations to run:", 100)
),
mainPanel(
plotOutput("plot")
)
))
)
这篇关于在R SHINY中读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!