如何在R Shiny应用程序中操作数据框

时间:2020-01-04 00:40:11

标签: shiny shinydashboard shiny-server shiny-reactivity shinyapps

请有关发光代码的助手。我想通过将数据帧输入分成列向量进行运算来处理数据帧输入,但是我一直收到此错误

Warning in <reactive>(...): NAs introduced by coercion

代码如下

 library(shiny)
ui <- fluidPage(

  # dataset
  data <- data.frame(e1 = c(3, 7, 2, 14, 66),
             e2 = c(2, 16, 15, 66, 30),
             n1 = c(18, 25, 45, 62, 81), 
             n2= c(20, 30, 79, 64, 89))   
# Application title
titlePanel("Demo"),

# Sidebar with a slider input for number of bins 
sidebarLayout(
  sidebarPanel(
     # Input: Upload file
    fileInput(inputId = 'file', label = 'upload the file')
    ),

 # Display Output
  mainPanel(
    uiOutput("final")
    )
  )
 )
# Define server logic required to draw a histogram
server <- function(input, output) {

   # separating the dataframe into 4 column vectors
   e1 <- reactive(as.numeric(input$file[,1]))
   e2 <- reactive(as.numeric(input$file[,2]))
   n1 <- reactive(as.numeric(input$file[,3]))
   n2 <- reactive(as.numeric(input$file[,4]))

   # File Upload function
   data <- reactive({
   file1 <- input$file
   if(is.null(file1)){return()}
   read.table(file = file1$datapath, sep = ',', header = TRUE)
   })


   output$result <- renderUI({
     y <- (e1()/n1()) - (e2()/n2())
    lg_y <- log(y)
    v2 <- ((n1() - e1())/e1() * n1()) + ((n2() - e2())/e2() * n2())
    w <- 1/v2
    w1 <- sum(w)
    w2 <- sum(w^2)
    c <- w1 - (w2/w1)
    s2 <- w * lg_y
    ybar <- sum(s2)/sum(w)
    Q <- sum(w*((lg_y - ybar)^{2}))# Cochrane homogeneity test statistic
    Q.pval <- reactive(pchisq(Q, k() - 1,lower.tail = FALSE))
    Isqd <- max(100*((Q-(k()-1))/Q),0)
   })
 }
 # Run the application 
 shinyApp(ui = ui, server = server)

我在该论坛上搜索了几乎所有问题,但没有看到问题的答案。请期待您的帮助

1 个答案:

答案 0 :(得分:0)

由于您未定义函数k(),因此仍然无法运行上面的代码。同样,仅供参考,您的renderUI设置为"result",而您的uiOutput设置为"final"

您会收到警告Warning in <reactive>(...): NAs introduced by coercion,因为您的真实数据集中可能包含非数字。您上面提供的数据集没有任何问题。

有两种前进方式:

1)在处理数据之前,编写一个删除所有非数字的函数。有关一些示例,请参见here

2)仅保留警告,毕竟这是一个警告,因此它不会阻止您的代码运行。当前,它将您的非数字变成NA

3)使用suppressWarnings(),但通常不建议这样做。

我确实有建议清理您的代码:

   # File Upload function
   data <- reactive({
   file1 <- input$file
   if(is.null(file1)){return()}
   read.table(file = file1$datapath, sep = ',', header = TRUE, stringsAsFactors = FALSE)
   })

# separating the dataframe into 4 column vectors
   e1 <- reactive(as.numeric(data()[,1]))
   e2 <- reactive(as.numeric(data()[,2]))
   n1 <- reactive(as.numeric(data()[,3]))
   n2 <- reactive(as.numeric(data()[,4]))