gpt4 book ai didi

R Shiny : How can I format choices in a a selectInput drop box?

转载 作者:行者123 更新时间:2023-12-02 07:26:10 26 4
gpt4 key购买 nike

我正在构建一个 Shiny 的页面,我想让用户对图形元素进行一些控制 - 颜色、符号大小等。我放入一个下拉框,让用户控制图形中点的颜色。我希望颜色的名称以颜色本身的形式出现。 ui.r有:

selectInput("PColor","Choose a Color:",
choices=list(HTML('<p style="color: blue"> blue </p>'),
HTML('<p style="color: red"> red </p>'),selected="blue")

但是,不会评估 HTML 代码。相反,下拉选项有 '<p style="color: blue"> blue </p>'红色也类似。我是否可以格式化此列表中的每个单独选项?

谢谢

最佳答案

以下解决方案应该适用于radioButtons():

radioButtons2 <- function(inputId, label, choices, selected){
temp.choices <- names(choices)
n <- length(choices)
names(temp.choices) <- paste0("ABCZYXWVU",1:n) -> temp.names
html <- as.character(radioButtons(inputId, label, temp.choices, selected=names(temp.choices[temp.choices==selected])))
for(i in 1:n){
html <- sub(paste0("<span>",temp.names[i],"</span>"), as.character(choices[[i]]), html)
}
attr(html,"html") <- TRUE
html
}

请注意,我已经颠倒了选择中名称的角色;它的工作原理如下:

    choices <- list(blue=HTML('<span style="color: blue"> blue </span>'), red=HTML('<span style="color:red"> red </span>'))
> cat(as.character(
+ radioButtons2("inputId","label",choices=choices, selected="blue")
+ ))
<div id="inputId" class="control-group shiny-input-radiogroup">
<label class="control-label" for="inputId">label</label>
<label class="radio">
<input type="radio" name="inputId" id="inputId1" value="blue" checked="checked"/>
<span style="color: blue"> blue </span>
</label>
<label class="radio">
<input type="radio" name="inputId" id="inputId2" value="red"/>
<span style="color:red"> red </span>
</label>
</div>

但是 selectInput() 的类似解决方案不起作用:html 代码被忽略。您可以尝试使用 selectInput2():

selectInput2 <- function(inputId, label, choices, selected = NULL, multiple = FALSE){
temp.choices <- names(choices)
n <- length(choices)
names(temp.choices) <- paste0("ABCZYXWVU",1:n) -> temp.names
html <- as.character(selectInput(inputId, label, temp.choices, selected=names(temp.choices[temp.choices==selected]), multiple))
for(i in 1:n){
html <- sub(temp.names[i], as.character(choices[[i]]), html)
}
attr(html,"html") <- TRUE
html
}
> cat(as.character(
+ selectInput2("inpuId", "label", choices, selected="blue")
+ ))
<label class="control-label" for="inpuId">label</label>
<select id="inpuId">
<option value="blue" selected="selected"><span style="color: blue"> blue </span></option>
<option value="red"><span style="color:red"> red </span></option>
</select>

此功能有效,但 html 代码在应用程序中消失(如浏览器中的“检查元素”所示)。如果您强制使用 html 代码,那么实际上 html 代码会出现在 selectInput 的标签中。

关于R Shiny : How can I format choices in a a selectInput drop box?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20079594/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com