问题描述
我想在DT中添加一列,该DT接受selectInput或numericInput,具体取决于变量.例如,给定以下DF:
I would like to add a column to a DT that accepts either selectInput or numericInput, depending on the variable.For example, given the following 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结合使用.
I would like to create an extra col in the DF (using DT
), with selectInput for var1
(choices= letters[1:3]) and numericInput for var2
.I have found here a great example for implementing selectInput, however I am not sure how it might be combined with numericInput.
任何帮助表示赞赏!
推荐答案
此处是.
使用 pivot_longer
代替 gather
,这是最新版本的 tidyr
推荐的.另外,在为新的 selector
列创建输入时,请检查变量 name
.如果它是 var1
,请使用 selectInput
,否则请使用 numericInput
.
Instead of gather
, using pivot_longer
which is recommended in latest version of tidyr
. In addition, when creating the inputs for the new selector
column, check the variable name
. If it is var1
use a selectInput
, otherwise use numericInput
.
否则,应该以类似的方式工作.
Otherwise, should work in a similar fashion.
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)
这篇关于在DT中嵌入具有混合numericInput和selectInput的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!