Shiny R:数据帧中的子集行

时间:2018-04-25 20:22:01

标签: r shiny subset

我试图通过使用Shiny中的选择输入小部件,按某些因子级别或这些级别的组运行模型。

当我按一个因子级别进行子集时,我得到了正确的模型结果。但是当我尝试运行包含所有因子水平或水平组的模型时,我没有得到正确的模型估计。

例如,正确的模型估计何时包含所有因子水平(即模型在整个数据帧上运行)是: enter image description here

但是当我运行我的应用程序并选择我的因子变量的所有级别(代表不同的地理区域)时,我获得了不同的结果: enter image description here

我的问题是如何指定我的反应子设置功能以适应所有因子水平或水平组?

各个模型的代码,包括因子级别的所有级别和模型供参考:

library(mlogit)
data("Heating", package = "mlogit")
mlogit(depvar ~ ic + oc | 0, data= Heating, shape = "wide", choice = "depvar", varying = c(3:12))
mlogit(depvar ~ ic + oc | 0, data= Heating[Heating$region=="ncostl" , ], shape = "wide", choice = "depvar", varying = c(3:12))
mlogit(depvar ~ ic + oc | 0, data= Heating[Heating$region=="scostl" , ], shape = "wide", choice = "depvar", varying = c(3:12))
mlogit(depvar ~ ic + oc | 0, data= Heating[Heating$region=="mountn" , ], shape = "wide", choice = "depvar", varying = c(3:12))
mlogit(depvar ~ ic + oc | 0, data= Heating[Heating$region=="valley" , ], shape = "wide", choice = "depvar", varying = c(3:12))

闪亮的代码:

### PART 1 - Load Libraries and Data
library(shiny)           # For running the app
library(mlogit)

#### data
data("Heating", package = "mlogit")

#### PART 2 - Define User Interface for application
ui <- fluidPage(

  ## Application title
  titlePanel("Housing Preference"),

  ## Sidebar with user input elements
  sidebarLayout(
    sidebarPanel(
      p("Select the inputs"), # Header
      # Speciality
      selectInput('regiontype', 'Region', choices = c("northern coastal region"= "ncostl", 
                                               "southern coastal region" = "scostl", 
                                               "mountain region"  = "mountn",
                                               "central valley region"= "valley"), multiple=TRUE, selectize=TRUE)

    ),

    ## Show a plot
    mainPanel(
      verbatimTextOutput("summary")
    )
  )
)

#### PART 3 - Define server logic required to run calculations and draw plots
server <- function(input, output) {

  output$summary <- renderPrint({

    df <- Heating

    ### Subset data
    df.subset <- reactive({ a <- subset(df, region == input$regiontype)
    return(a)})

    ### Model 
    estimates <- mlogit(depvar ~ ic + oc | 0, data= df.subset(), shape = "wide", choice = "depvar", varying = c(3:12))
    summary(estimates)


  })
}

### PART 4 - Run the application 
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:1)

问题在于你在子集中使用==

让我们来看看您的数据:

table(Heating$region)

#> valley scostl mountn ncostl 
#>    177    361    102    260 

900行,scostlncostl占您行的621行。但是,当我在传递匹配向量的子集中返回时,只返回305。

nrow(subset(Heating, region == c("ncostl","scostl")))
#> [1] 305

发生什么事了?为什么不是621? 矢量回收正在咬你。由于Heating$regionc("ncostly","scostl")的长度不同,因此较短的长度会重复,直到长度相同为止。因此,您实际上正在过滤ncostlscostl的模式并返回这些匹配。

相反,您希望使用%in%运算符。

nrow(subset(Heating, region %in% c("ncostl","scostl")))
#> [1] 621

现在,没有矢量回收,因为Heating$region的每个元素都会检查您提供的列表中的成员资格。

您获取矢量的原因是闪亮的多个selectInput的输出。

相关问题