我有一个名为inputs
的嵌套列表:
library(htmltools)
library(shiny)
inputs = tagList(
selectInput('first', 'FIRST', letters),
checkboxInput('second', 'SECOND')
)
str(inputs, max.level = 1)
List of 2
$ :List of 3
..- attr(*, "class")= chr "shiny.tag"
..- attr(*, "html_dependencies")=List of 1
$ :List of 3
..- attr(*, "class")= chr "shiny.tag"
- attr(*, "class")= chr [1:2] "shiny.tag.list" "list"
我想修改所有具有类shiny.tag
且其name
元素等于label
的子列表(有关此类子列表的示例,请参见inputs[[1]][["children"]][[1]]
),但保留这样做时,列表的原始结构。
为此,我定义了一个递归函数hideLabel
:
hideLabel <- function(tag.list) {
lapply(tag.list, function(x) {
if(inherits(x, 'shiny.tag')) {
if(x$name == 'label') {
tagAppendAttributes(x, style = 'display:none;')
} else {
hideLabel(x$children)
}
} else {
return(x)
}
})
}
以下是将hideLabel应用于输入列表的输出:
res = hideLabel(inputs)
str(res, max.level = 1)
List of 2
$ :List of 2
$ :List of 1
如上所示,hideLabel不返回与原始列表输入结构相同的列表(将第一个代码块中str的输出与上面第三个块中str的输出进行比较)。我想知道是否有人可以帮助我理解该功能为何执行此操作以及如何对其进行修改?我尝试将其重写几次都无济于事。
更新:
考虑了函数在每个阶段返回的内容后,我开始使用它。这是更新的功能:
hideLabel <- function(x) {
children = x$children
x$children = lapply(children, function(y) {
if(inherits(y, 'shiny.tag')) {
if(y$name == 'label') tagAppendAttributes(y, style = 'display:none;') else hil(y)
} else y
})
return(x)
}
这将保留原始列表的结构:
inputs_new = lapply(inputs, hideLabel)
str(inputs, max.level = 1)
List of 2
$ :List of 3
..- attr(*, "class")= chr "shiny.tag"
..- attr(*, "html_dependencies")=List of 1
$ :List of 3
..- attr(*, "class")= chr "shiny.tag"
- attr(*, "class")= chr [1:2] "shiny.tag.list" "list"
注意:整个列表的类别从shiny.tag.list
更改为list
。有人知道如何防止这种情况发生吗?我知道我可以使用do.call(tagList, inputs_new)
手动重新添加shiny.tag.list
类,但这似乎很麻烦。