我想设计一个使用Shiny的应用程序,该应用程序允许用户为输入值添加书签。但是,我发现如果更改的输入格式,则numericInput
书签将无法正常工作。
根据此链接(https://beta.rstudioconnect.com/barbara/format-numbers/)格式化的输入numericInput
。我创建了一个js
名为number_format.js
的文件,并将该文件存储在目录中www
。代码如下。
$(document).ready(function() {
// Helper function to guarantee cross-browser compatibility
// adapted from: http://stackoverflow.com/a/16157942
function localeString(x, sep, grp) {
var sx = (''+x).split('.'), s = '', i, j;
sep || (sep = ','); // default separator
grp || grp === 0 || (grp = 3); // default grouping
i = sx[0].length;
while (i > grp) {
j = i - grp;
s = sep + sx[0].slice(j, i) + s;
i = j;
}
s = sx[0].slice(0, i) + s;
sx[0] = s;
return sx.join('.');
}
// To change Number's input field (lose arrows and other functionality)
$('#Number')[0].type = 'text';
// To format the number when the app starts up
$('#Number').val(localeString($('#Number').val()));
// To format the number whenever the input changes
$('#Number').keyup(function(event) {
$(this).val(localeString($(this).val().replace(/,/g, '')));
});
});
然后是shiny
带有numericInput
和书签按钮的代码。
# Load the packages
library(shiny)
library(shinydashboard)
# User Interface
ui <- function(request) {
dashboardPage(
header = dashboardHeader(title = "Bookmark Example"),
sidebar = dashboardSidebar(
sidebarMenu(
menuItem(
text = "Example",
tabName = "tab1"
),
bookmarkButton()
)
),
body = dashboardBody(
# Change tags
tags$head(tags$script(src = "number_format.js")),
tabItems(
tabItem(
tabName = "tab1",
numericInput(inputId = "Number", label = "Number:", value = NA)
)
)
)
)
}
server <- function(input, output, session){
}
# Run the app
shinyApp(ui, server, enableBookmarking = "url")
通过运行此代码,的输入numericInput
具有正确的格式,但是书签无法正常工作。我们可以通过注释掉该行tags$head(tags$script(src = "number_format.js")),
来比较结果,以查看如果数字未自动格式化,则书签将起作用。
有没有办法让自动格式化和书签同时工作?
这是一种解决方法:
# Load the packages
library(shiny)
library(shinydashboard)
# User Interface
ui <- function(request) {
dashboardPage(
header = dashboardHeader(title = "Bookmark Example"),
sidebar = dashboardSidebar(
sidebarMenu(
menuItem(
text = "Example",
tabName = "tab1"
),
bookmarkButton()
)
),
body = dashboardBody(
# Change tags
tags$head(tags$script(src = "number_format.js")),
tabItems(
tabItem(
tabName = "tab1",
numericInput(inputId = "Number", label = "Number:", value = NA)
)
)
)
)
}
server <- function(input, output, session){
bigMarkInputs <- c("Number")
setBookmarkExclude(bigMarkInputs)
onBookmark(function(state){
for (bigMarkInput in bigMarkInputs){
state$values[[bigMarkInput]] <- isolate({input[[bigMarkInput]]})
}
})
onRestore(function(state){
for (bigMarkInput in bigMarkInputs){
updateNumericInput(session, inputId = bigMarkInput, value = state$values[[bigMarkInput]])
}
})
}
# Run the app
shinyApp(ui, server, enableBookmarking = "url")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句