我正在 R 中使用 ShinyApps。我使用 sliderInput,其值在 2010 到 2015 之间,因为您选择了年份。 我的数据是这样的:
> data
nomMun 2010 2011 2012 2013 2014 2015 lon lat
1 ABRERA 0 0 5 3 2 0 1.12 40.1
2 AGER 2 0 1 1 0 0 1.54 40.2
3 AGRAMUNT 1 1 0 2 0 1 1.36 40.3
我想使用名称与输入值相同的列(如果滑块值为 2010,则为 data$2010)。我需要选择此列的值来指示我在地图中添加的圆的半径。
output$MapPlot1<-renderLeaflet({
any<-input$any1
content<-paste(data$nomMun,paste("Accidents",data$any))
leaflet(data) %>% addTiles() %>%
addCircles(lng = ~lon, lat = ~lat, weight = 1, stroke=TRUE,radius =
~sqrt(any)*100,popup = content, fillOpacity = 0.2)
})
将数值转换为字符后,可以用
[[
选择:
addCircles(
lng = ~lon
, lat = ~lat
, weight = 1
, stroke = TRUE
, radius = ~sqrt(data[[paste0(input$any1)]])*1000
, popup = paste(data$nomMun, paste("Accidents", data[[paste0(any)]]))
, fillOpacity = 0.2
)
更好的方法
更好的方法是融合数据,这样你就可以在年份列上进行过滤,这样你就可以在传单函数中始终引用同一列,并且数据会产生差异。
library("shiny")
library("data.table")
library("purrr")
library("leaflet")
data <- fread('nomMun,2010,2011,2012,2013,2014,2015,lon,lat
ABRERA,0,0,5,3,2,0,1.12,40.1
AGER,2,0,1,1,0,0,1.54,40.2
AGRAMUNT,1,1,0,2,0,1,1.36,40.3', sep = ",", header = TRUE)
# set any 0 values to NA so they'll be dropped when we convert to long form
data[data == 0] <- NA
molten_data <- melt.data.table(
data = data
, id.vars = c("nomMun", "lon", "lat")
, variable.name = "year"
, variable.factor = FALSE
, na.rm = TRUE
)
molten_data[, `:=`(
year = as.integer(year)
, content = paste(nomMun, paste("Accidents", value))
)]
year_range <- range(molten_data$year)
ui <- fluidPage(
sliderInput(
inputId = "any1"
, label = "Year"
, min = year_range[1]
, max = year_range[2]
, value = year_range[1]
, step = 1
, sep = ""
)
, leafletOutput("MapPlot1")
)
server <- function(input, output, session) {
year_data <- reactive({
molten_data[year == input$any1]
})
output$MapPlot1 <- renderLeaflet({
year_data() %>%
leaflet() %>%
addTiles() %>%
addCircles(
lng = ~lon
, lat = ~lat
, weight = 1
, stroke = TRUE
, radius = ~sqrt(value)*1000
, popup = ~content
, fillOpacity = 0.2
)
})
}
shinyApp(ui, server)