R Shiny $运算符对原子向量无效

时间:2013-07-16 06:38:27

标签: r shiny

我正在尝试构建一个样本量计算器并且我一直收到错误

 $ operator is invalid for atomic vectors

我已尝试过所有内容,但此错误仍然存​​在。用户输入一些值,闪亮的反应性获取值,检查用户想要计算的值并返回结果。可能有什么不对?我的代码如下:


Global.R

#options(shiny.trace = TRUE)

#check for and/or install dependencies
need<-c("shiny","ggplot2","pwr","googleVis") # some more should auto load...
for(i in 1:length(need)){
  if(require(need[i], character.only = TRUE)==FALSE){install.packages(need[i]);library(need[i], character.only = TRUE)} else { library(need[i],character.only = TRUE)}
}

library(googleVis)
library(shiny)
library(ggplot2)
library(pwr)

# load code for custom functions
source("plot.R") # for using ggplot

#data <- read.csv("dataset.csv",headers=T)

calculationTypes <-c("default","2p.test","2p2n.test",
                    "anova.test","chisq.test",  "f2.test",
                    "p.test","r.test","t.test","t2n.test")
names(calculationTypes) <- c("Select Function Type",
                             "Proportions (equal n)",
                             "Two proportions (unequal n)",
                             "Balanced one way ANOVA",
                             "Chi-square test",
                             "General linear model",
                             "Proportion (one sample)",
                             "Correlation",
                             "T-tests (one sample, 2 sample, paired)",
                             "T-test (two samples with unequal n)")
valueCalculate <-c("sampleSize","alternateSampleSize","effectSize","significanceLevel","samplePower",  "correlation")
names(valueCalculate) <- c("Sample Size","Second Sample Size","Effect Size","Significance Level","Power","Correlation")

customHeaderPanel <- function(title,windowTitle=title){
  tagList(
    tags$head(
      tags$title(windowTitle),
      tags$link(rel="stylesheet", type="text/css",href="app.css")
    ),
    HTML("<div class='row-fluid'>"),
        HTML("<div class='span9'>"),
            HTML("<div class='row-fluid' id='header'>"),
                div(class = "span3",imageOutput("logo", height = "153px", width="272px")),
                div(class = "span6",h1(title)),
            HTML("</div>"),
        HTML("</div>"),
    HTML("</div>")
  )
}

server.R

shinyServer(function(input, output, session) {

    sigLevel <- NULL
    pwr <- NULL
    sample <- NULL
    altSample <- NULL
    effSize <- NULL

    observe({
        if(input$calculate == 0){ #check if this is first run
            return()   
        }
        isolate({
            # Read inputs and save values to database here
        })
    })

    #KEMRI wellcome Trust programme logo
    output$logo <- renderImage({
      filename <- 'logo.png'
      list(src = filename,
           contentType = 'image/png',
           width = 272,
           height = 153,
           alt = "KEMRI-Wellcome Trust Programme")

    }, deleteFile = FALSE)

    #Capture user input for calculating the sample size
    sampleSize <- reactive ({ as.numeric(input$sampleSize) })
    alternateSampleSize <- reactive ({ input$alternateSampleSize }) # conditional for t2n.test 
    effectSize <- reactive ({ as.numeric(input$effectSize) })
    significanceLevel <- reactive ({ as.numeric(input$significanceLevel) })
    degFreedom <- reactive ({ as.numeric(input$degFreedom) })
    numerator <- reactive ({ as.numeric(input$numerator) })
    denominator <- reactive ({ as.numeric(input$denominator) })
    samplePower <- reactive ({ as.numeric(input$samplePower) })
    groupCount <- reactive ({ if(is.na(input$groupCount))
                                 NULL
                              else
                                as.numeric(input$groupCount) 
                            }) #conditional for annova
    ttestType <- reactive ({ input$ttestType })
    correlation <- reactive ({ as.numeric(input$correlation) }) #should be between 0 and 1
    valueToCalculate <- reactive ({ input$valueToCalculate })

    # Return the requested calculation
    powerAnalysisFunction <- reactive({ input$powerAnalysisFunction })

    output$calculatedSampleSize <- renderUI({

      sigLevel <- significanceLevel()
      pwr <- samplePower()
      sample <- sampleSize()
      altSample <- alternateSampleSize()
      effSize <- effectSize()
      calcVal <- valueToCalculate()
      linearRegDenom <- denominator()
      linearRegNum <- numerator()
      freedomDegrees <- degFreedom()

      if(calcVal=='sampleSize')
        sample <- NULL
      else if(calcVal =='alternateSampleSize')
        altSample <- NULL
      else if(calcVal =='effectSize')
        effSize <- NULL
      else if(calcVal =='significanceLevel')
        sigLevel <- NULL
      else if(calcVal =='samplePower')
        pwr <- NULL

      if(powerAnalysisFunction() =='2p.test'){          #two proportions (equal n)
        print(pwr.2p.test(h =effSize , n =sample , sig.level = sigLevel, power = pwr ))      
      }else if(powerAnalysisFunction() =='2p2n.test'){      #two proportions (unequal n)
        print(pwr.2p2n.test(h =effSize , n1 =sample , n2 =altSample , sig.level =sigLevel , power =pwr )) 
        }else if(powerAnalysisFunction() == 'anova.test'){  #balanced one way ANOVA 
          print(pwr.anova.test(k = groupCount(), n = sample, f = effSize, sig.level = sigLevel, power=pwr )) 
        }else if(powerAnalysisFunction() == 'chisq.test'){  #chi-square test
        print(pwr.chisq.test(w =effSize, N =sample , df =freedomDegrees , sig.level =sigLevel, power =pwr ))
        }else if(powerAnalysisFunction() == 'f2.test'){         #general linear model
          print(pwr.f2.test(u = linearRegNum, v = linearRegDenom, f2 =effSize , sig.level = sigLevel , power =pwr )) 
        }else if(powerAnalysisFunction() == 'p.test'){        #proportion (one sample)
          print(pwr.p.test(h = effSize, n =sample , sig.level =sigLevel, power = pwr ))
        }else if(powerAnalysisFunction() == 'r.test'){        #correlation
          print(pwr.r.test(n = sample, r = correlation(), sig.level = sigLevel, power = pwr ))
        }else if(powerAnalysisFunction() == 't.test'){      #t-tests (one sample, 2 sample, paired)
          print(pwr.t.test(n = sample , d = effSize , sig.level = sigLevel , power = pwr , type = c("two.sample", "one.sample", "paired"))) 
        }else if(powerAnalysisFunction() == 't2n.test'){        #t-test (two samples with unequal n)        
          print(pwr.t2n.test(n1 = sample , n2= altSample , d = effSize , sig.level = sigLevel, power = pwr ))
        }
    })

  })

ui.R

# Define UI for application that plots random distributions
shinyUI(pageWithSidebar(

  # Application title
  customHeaderPanel("KEMRI Wellcome Trust Programme"),

  # Sidebar with a slider input for number of observations
  sidebarPanel(
    selectInput("powerAnalysisFunction","Power Calculations For",
                choices = calculationTypes),
    sliderInput("sampleSize", "Sample Size:", 
                min=0, max=1000, value=20),
    sliderInput("alternateSampleSize", "Second Sample Size:", 
                min=0, max=1000, value=20),
    sliderInput("effectSize", "Effect Size:", 
                min=0, max=1, value=0.80, step = 0.05),
    sliderInput("significanceLevel", "Significance Level:", 
                min=0, max=1, value=0.05, step = 0.05),
    sliderInput("samplePower", "Power:", 
                min=0, max=1, value=0.5, step = 0.05),
    sliderInput("correlation", "Correlation:", 
                min=0, max=1, value=0.5, step = 0.05),
    sliderInput("degFreedom", "Chi-square:Degrees of freedom", 
                min=0, max=10, value=5, step = 1),
    sliderInput("numerator", "Linear Model:Numerator(Degrees of freedom):", 
                min=0, max=1, value=0.5, step = 0.05),
    sliderInput("denominator", "Linear Model:Denominator(Degrees of freedom):", 
                min=0, max=1, value=0.5, step = 0.05),
    numericInput("groupCount", "Group Count (For Annova)",2),
    selectInput("valueToCalculate","Value to calculate",
                choices = valueCalculate),
    br(),
    actionButton("calculate", "Calculate")
  ),

  mainPanel(
    tabsetPanel(id = "tabs",
                tabPanel(id="sampleSize","Sample Size Calc",htmlOutput("calculatedSampleSize"))
    )
  )
))#End of UI

这段代码可能有什么问题?提到哪些原子载体?如何纠正此错误?

2 个答案:

答案 0 :(得分:1)

问题在于反应式renderUI功能。计算结果属于power.htest类。为了解决这个错误,我在server.R

中做了以下更改
output$calculatedSampleSize <- renderUI({    
results <- NULL
  sigLevel <- significanceLevel()
  pwr <- samplePower()
  sample <- sampleSize()
  altSample <- alternateSampleSize()
  effSize <- effectSize()
calcVal <- valueToCalculate()
linearRegDenom <- denominator()
linearRegNum <- numerator()
  freedomDegrees <- degFreedom()

if(calcVal=='sampleSize')
  sample <- NULL
else if(calcVal =='alternateSampleSize')
  altSample <- NULL
else if(calcVal =='effectSize')
  effSize <- NULL
else if(calcVal =='significanceLevel')
  sigLevel <- NULL
else if(calcVal =='samplePower')
  pwr <- NULL

if(powerAnalysisFunction() =='2p.test'){          #two proportions (equal n)
  results <- pwr.2p.test(h =effSize , n =sample , sig.level = sigLevel, power = pwr )      
}else if(powerAnalysisFunction() =='2p2n.test'){    #two proportions (unequal n)
  results <- pwr.2p2n.test(h =effSize , n1 =sample , n2 =altSample , sig.level =sigLevel , power =pwr ) 
}else if(powerAnalysisFunction() == 'anova.test'){  #balanced one way ANOVA 
  results <- pwr.anova.test(k = groupCount(), n = sample, f = effSize, sig.level = sigLevel, power=pwr ) 
}else if(powerAnalysisFunction() == 'chisq.test'){  #chi-square test
  results <- pwr.chisq.test(w =effSize, N =sample , df =freedomDegrees , sig.level =sigLevel, power =pwr )
}else if(powerAnalysisFunction() == 'f2.test'){         #general linear model
  results <- pwr.f2.test(u = linearRegNum, v = linearRegDenom, f2 =effSize , sig.level = sigLevel , power =pwr ) 
}else if(powerAnalysisFunction() == 'p.test'){        #proportion (one sample)
  results <- pwr.p.test(h = effSize, n =sample , sig.level =sigLevel, power = pwr )
}else if(powerAnalysisFunction() == 'r.test'){        #correlation
  results <- pwr.r.test(n = sample, r = correlation(), sig.level = sigLevel, power = pwr )
}else if(powerAnalysisFunction() == 't.test'){      #t-tests (one sample, 2 sample, paired)
  results <- pwr.t.test(n = sample , d = effSize , sig.level = sigLevel , power = pwr , type = c("two.sample", "one.sample", "paired")) 
}else if(powerAnalysisFunction() == 't2n.test'){        #t-test (two samples with unequal n)        
  results <- pwr.t2n.test(n1 = sample , n2= altSample , d = effSize , sig.level = sigLevel, power = pwr )
}else{
  results <- " "
}    
return(tags$div(results))
})

答案 1 :(得分:0)

ui.R

中没有相应的条目
ttestType <- reactive ({ input$ttestType })