r语言 - 在DT中嵌入带有混合数字输入和选择输入的列



我想在DT中添加一列,该列根据变量接受selectInput或numericInput。例如,给定以下DF:

df1 <- tibble(

var1 = sample(letters[1:3],10,replace = T),
var2 = runif(10, 0, 2),
id=paste0("id",seq(1,10,1))
)
DF=gather(df1, "var", "value", -id)

我想在DF中创建一个额外的col(使用DT),为var1使用selectInput(选择=字母[1:3])和为var2使用数字输入。我在这里找到了一个实现selectInput的好例子,但是我不确定它如何与numericInput结合使用。

感谢任何帮助!

以下是该回答的改编版。

代替gather,使用tidyr最新版本中推荐的pivot_longer。此外,在为新的selector列创建输入时,检查变量name。如果是var1,使用selectInput,否则使用numericInput

否则,应该以类似的方式工作

library(shiny)
library(DT)
library(tidyverse)
df1 <- tibble(
var1 = sample(letters[1:3],10,replace = T),
var2 = runif(10, 0, 2),
id=paste0("id",seq(1,10,1))
)
# gather is retired, switch to pivot_longer
DF = pivot_longer(df1, cols = -id, names_to = "name", values_to = "value", values_transform = list(value = as.character))
ui <- fluidPage(
title = 'selectInput or numericInput column in a table',
DT::dataTableOutput('foo'),
verbatimTextOutput('sel')
)
server <- function(input, output, session) {
for (i in 1:nrow(DF)) {
if (DF$name[i] == "var1") {
DF$selector[i] <- as.character(selectInput(paste0("sel", i), "", choices = unique(df1$var1), width = "100px"))
} else {
DF$selector[i] <- as.character(numericInput(paste0("sel", i), "", NULL, width = "100px"))
}
}
output$foo = DT::renderDataTable(
DF, escape = FALSE, selection = 'none', server = FALSE,
options = list(dom = 't', paging = FALSE, ordering = FALSE),
callback = JS("table.rows().every(function(i, tab, row) {
var $this = $(this.node());
$this.attr('id', this.data()[0]);
$this.addClass('shiny-input-container');
});
Shiny.unbindAll(table.table().node());
Shiny.bindAll(table.table().node());")
)
output$sel = renderPrint({
str(sapply(1:nrow(DF), function(i) input[[paste0("sel", i)]]))
})
}
shinyApp(ui, server)

最新更新