简体   繁体   English

将代码放在输入文件上的位置(Shiny,R)

[英]where to put the code working on input file (Shiny, R)

I have difficulties putting some code into a separate file. 我很难将一些代码放入单独的文件中。

The following code works: 以下代码有效:

ui.R 用户界面

library(shiny)

shinyUI(fluidPage(
    titlePanel("Uploading Files"),

    sidebarLayout(

        sidebarPanel(

            fileInput('file1', 'Choose CSV File',
                      accept=c('text/csv', 
                               'text/comma-separated-values,text/plain', 
                               '.csv')),

            tags$hr()

        ),
        mainPanel(
            tableOutput('contents')
        )
    )
))

server.R 服务器

library(shiny)
library(dplyr)

shinyServer(function(input, output) {

    getData <- reactive({
        inFile <- input$file1
        if (is.null(inFile)) return(NULL)
        data = read.csv(inFile$datapath)
        ### CleanData
        data = data %>%
            mutate_each(funs(toupper)) %>%    
            mutate_each(funs(gsub("[[:punct:]]", " ", .))) %>%
            mutate_each(funs(str_trim)) %>%
            mutate_each(funs(rm_white)) %>%
            sample_frac(1) 

    })

    output$contents = renderTable({
        getData()

    })

})

But if I put some code into a separate file, it doesn't work. 但是,如果我将一些代码放入一个单独的文件中,它将无法正常工作。

ui.R doesn't change ui.R不变

server.R 服务器

library(shiny)
library(dplyr)

shinyServer(function(input, output) {

    getData <- reactive({
        inFile <- input$file1
        if (is.null(inFile)) return(NULL)
        data = read.csv(inFile$datapath)
        ### CleanData
        source('CleanData.R')

    })

    output$contents = renderTable({
        getData()

    })

})

CleanData.R (in the same directory in laptop) CleanData.R(在笔记本电脑的同一目录中)

data = data %>%
    mutate_each(funs(toupper)) %>%    
    mutate_each(funs(gsub("[[:punct:]]", " ", .))) %>%
    mutate_each(funs(str_trim)) %>%
    mutate_each(funs(rm_white)) %>%
    sample_frac(1) 

It doesn't work, giving an error 它不起作用,出现错误

Error in UseMethod("tbl_vars") : 
  no applicable method for 'tbl_vars' applied to an object of class "function"

Somebody know how to fix this? 有人知道如何解决这个问题? Thanks a lot 非常感谢

You are getting that error because when you source the CleanData.R, it is evaluated in the global environment where data hasn't been defined by you, so it is referring to the function data . 你得到的错误,因为当你source的CleanData.R,它是在全球环境评估的data尚未由您定义,所以它指的是函数data You can add local=TRUE to the source call to have it evaluated in the calling environment, 您可以将local=TRUE添加到source调用中,以在调用环境中对其进行评估,

    source('CleanData.R', local=TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM