Shiny离线环境下DT渲染tbl_df报错,求转spec_tbl_df方案
解决Shiny离线运行时DT表格渲染报错问题
问题背景
Shiny应用在服务器上运行正常,但离线环境下渲染DT表格时触发错误:
DataTables warning: table id=DataTables_Table_0 - Error in if (!searchable[j]) next: argument is of length zero
直接使用table()返回的tbl_df/tbl/data.frame类对象渲染时会报错,但将该对象写入CSV再读取得到的spec_tbl_df/tbl_df/tbl/data.frame类对象却能正常渲染。原应用代码超1500行,无法生成最小复现示例。
可行解决办法
无需通过写入再读取CSV的冗余操作,直接用以下方法将table()的结果转换为spec_tbl_df类:
方法1:用readr::type_convert()自动转换
利用readr包的type_convert()函数,自动推断列类型并添加列规格(spec),直接将普通tibble转为spec_tbl_df:
output$table_coloured = DT::renderDataTable({ # 直接转换table()的结果为spec_tbl_df table_data = readr::type_convert(table()) datatable(table_data, filter = c("top"), rownames = FALSE, escape = FALSE, options = list(paging = FALSE, autoWidth = TRUE, searching = TRUE, search = list(regex = TRUE, scrollX = TRUE), server = FALSE ) ) %>% formatStyle(columns = c(2), width='100px') %>% formatStyle("features_coloured","white-space"="nowrap") %>% formatStyle("sentence_coloured","white-space"="nowrap") %>% formatStyle("verb_form", "white-space"="nowrap") %>% formatStyle("has_class", "white-space"="nowrap") %>% formatStyle("neg", "white-space"="nowrap") %>% formatStyle("text_comments_extracted", "white-space"="nowrap") %>% formatStyle("rel_clause", "white-space" = "nowrap") %>% formatStyle("tags", "white-space"="nowrap") %>% formatStyle("mood", "white-space"="nowrap") %>% formatStyle("VCexpansion", "white-space"="nowrap") %>% formatStyle("multipleclauses", "white-space"="nowrap") %>% formatStyle(8, `border-right` = "solid 2px") })
方法2:手动构造spec_tbl_df
如果需要自定义列类型,可以先构建列规格,再用spec_tbl_df()创建对象:
output$table_coloured = DT::renderDataTable({ tbl_data = table() # 手动定义列规格,根据实际列调整类型 tbl_spec = readr::cols( features_coloured = readr::col_character(), sentence_coloured = readr::col_character(), verb_form = readr::col_character(), # 其他列依次定义 ) # 转换为spec_tbl_df table_data = readr::spec_tbl_df(tbl_data, spec = tbl_spec) # 后续datatable渲染代码同上 })
方法3:先转普通data.frame再转回spec_tbl_df
如果前两种方法无效,可先将tibble转为普通data.frame,再用type_convert()添加规格:
table_data = readr::type_convert(as.data.frame(table()))
原理说明
spec_tbl_df是带有明确列类型规格的tibble,DT在离线环境下对这种结构的列类型信息处理更稳定,避免了直接处理普通tibble时的列类型推断异常,从而解决报错问题。
内容的提问来源于stack exchange,提问作者Nick Riches
相关产品推荐
相关产品推荐

