[英]R change columns types using shiny, rhandson and DT
我有一个闪亮的应用程序,用户可以在其中将他的 csv 上传到user_table()
反应式表达式中,然后使用 DT renderDataTable()
将其显示给用户; 还有来自user_table()
的列类型的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() }
})
现在我正在尝试执行以下操作:单击应用按钮后,使用用户更改的列类型创建一个新表,但我不确定应该如何正确完成。 我应该使用另一个反应式表达来做到这一点吗? 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 不会对用户输入做出反应; 它只是将列类型更改为与它们已经相同的类型。 任何解决方法?
似乎是这样工作的:
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()) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.