R Shiny Reactive:从txt文件导入表时未找到对象

时间:2016-09-22 14:44:22

标签: r shiny leaflet

如果我通过" data.table(...)"在脚本中定义数据表,则以下脚本可以正常运行。 对于较大的数据集,使用" read.table(...)"从文本文件导入数据更为舒适。

不幸的是,从文本文件导入数据时,脚本无法正常运行。错误消息是:"警告:grepl中出错:对象'材料'找不到"

专栏"材料"在这种情况下无法识别。你知道如何解决这个问题吗?

#This is the content of example_data.txt (sep. by tabulator):
#id londd   latdd   material    application name    color
#1  20  60  stone   a   1   red
#2  38  56  water,sand  b   2   green
#3  96  30  sand    c   3   blue
#4  32  31  wood    d   4   yellow

# Filtermap
library(data.table)
library(shiny)
library(dplyr)
library(leaflet)

#mydat <- data.table( id=c(1,2,3,4),
#                 londd=c(20, 38, 96, 32),
#                 latdd=c(60, 56, 30, 31),
#                 material=c("stone", "water,sand", "sand", "wood"),
#                 application=c("a","b","c","d"))

mydat <- read.table("example_data.txt",header=TRUE,sep="\t",
encoding="UTF-8")

#Set up ui
ui <- shinyUI(fluidPage(
  sidebarPanel(h5("", width=2),
           checkboxGroupInput(inputId="MatFlag",label=h4("Material"), 
               choices=setNames(object=c("stone","water","sand", "wood"),
               nm=c("stone", "water", "sand", "wood")),
           ),
           checkboxGroupInput(inputId="AppFlag",label=h4("Application"), 
               choices=setNames(object=c("a","b","c","d"),
               nm=c("a","b","c","d")),
           ),
           position="left"),

#App mainPanel content and styles
mainPanel(fluidRow(leafletOutput(outputId="lmap")))
))

#Set up server
server <- function(input, output){
#Build leaflet map
lmap <- leaflet(data=mydat)%>%
addProviderTiles("Stamen.TonerLite", 
                 options =providerTileOptions(noWrap = TRUE)) %>%
fitBounds(~min(londd), ~min(latdd), ~max(londd), ~max(latdd))

#Filter data
datFilt <- reactive({
MatSearch <- paste0(c('xxx',input$MatFlag),collapse = "|")
MatSearch <- gsub(",","|",MatSearch)
mydat[grepl(MatSearch,material) & application %in% input$AppFlag]
})

#Add markers based on selected flags
observe({
  if(nrow(datFilt())==0) {
      print("Nothing selected")
      leafletProxy("lmap") %>%
      clearMarkerClusters()
  } else { 
      print("Something Selected")
      leafletProxy("lmap", data=datFilt()) %>% 
      clearMarkerClusters() %>% 
      addCircleMarkers(lng=~londd, lat=~latdd,
                     clusterOptions=markerClusterOptions(), weight=3,
                     color="#33CC33", opacity=1, fillColor="#FF9900", 
                     fillOpacity=0.8)
  }
})

output$lmap <- renderLeaflet(lmap)
}

#Run app
shinyApp(ui = ui, server = server)

0 个答案:

没有答案