gpt4 book ai didi

R 使用 shiny、rhandson 和 DT 更改列类型

转载 作者:行者123 更新时间:2023-12-04 02:04:56 24 4
gpt4 key购买 nike

我有一个 Shiny 的应用程序,用户可以将他的 csv 上传到 user_table()响应式(Reactive)表达式,然后使用 DT renderDataTable() 显示给用户;还有 RHandsontable,其中包含 user_table() 中的列类型。用户应该能够更改 RHandsontable 中的值并单击“应用”按钮,以将更改应用到他的表。 (即有一个“数字”列,他想将其更改为“字符”)。以下是为用户呈现 DT 的方式:

main_table <- DT::renderDataTable({
datatable(
user_table()
)
})

这是 handsontable 的工作原理:

dataTypes <- c("integer", "numeric", "factor", "character", "logical")
handsontable <- renderRHandsontable({
if (!is.null(input$uploaded_file)) {
if (is.null(input$hottest)) {
DF = data.frame(Type = cbind(lapply(user_table(), typeof)),
stringsAsFactors = TRUE)
} else {
DF = hot_to_r(input$hottest)
}
DF$Type = factor(DF$Type, dataTypes)
rhandsontable(DF, readOnly = FALSE) %>%
hot_table(stretchH = 'all', rowHeaderWidth = 120) %>%
hot_context_menu(allowRowEdit = FALSE, allowColEdit = FALSE)
}
else { return() }
})

现在我正在尝试执行以下操作:单击应用按钮后,创建一个包含用户更改的列类型的新表,但我不确定应该如何正确完成。我应该使用另一个 react 表达式来做到这一点吗? observeEvent 是否适合用于按钮 onclick 事件?如果不清楚,请询问。提前致谢!

编辑:我在浏览了一段时间后想到了这个功能:

convert.types <- function(obj, types){
for(i in length(obj)){
func <- switch(types[i],
integer = as.integer,
numeric = as.numeric,
factor = as.factor,
character = as.character,
logical = as.logical)
obj[,i] <- func(obj[,i])
}
obj
}

并将其与 observeEvent 一起使用:

observeEvent(input$button_table_convertion, {
hottestVector <- as.vector(t(hot_to_r(input$hottest)))
new_table <- convert.types(as.data.frame(user_table()), hottestVector)

不过,Rhandsontable 不会对用户输入使用react;它只是将列类型更改为它们已经存在的类型。任何解决方法?

最佳答案

似乎是这样工作的:

  new_table <- eventReactive(input$button_table_convertion, {
hottestVector <- as.vector(t(hot_to_r(input$handsontypes)))
convert.types(data.frame(user_table()), hottestVector)
})
output$secondtable <- DT::renderDataTable({ datatable(new_table()) })

关于R 使用 shiny、rhandson 和 DT 更改列类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44180603/

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