r - R 有光泽;在渲染中全局定义 NA 行为
问题描述
在制作包含许多包含一些 NA 值的表的 Shiny 应用程序时,全局定义 NA 的打印方式可能会有所帮助,例如renderTable
.
举个例子:
library(shiny)
ui <- fluidPage(
column(2,uiOutput("ourTable")),
column(2,uiOutput("ourTable2"))
)
server <- function(input, output) {
data<-data.frame(A=1:6, B=LETTERS[11:16], C=c(1,2,"A", "B", NA, NA))
output$ourTable<-renderTable({data})
output$ourTable2<-renderTable({data}, na="")
}
shinyApp(ui = ui, server = server)
这呈现如下:
理想情况下,我想添加一行代码(在服务器中或在 ui 中),以便所有表都呈现为ourTable2
,也就是说,无需NA
在输出中打印,也无需为我添加的每个表明确指定这一点。
解决方案
如果您愿意,可以在 global.R 文件(或 server.R)文件中定义以下内容。如果整个表为 NA,这将适用于您的表并返回“”。如果您传递复杂的对象,例如嵌入式列表列表,则需要更复杂一些。但是,在 OP 中打印 data.frame 将起作用。
在 global.R (或其他地方):
format.NAs <- function(x) {
if (identical(x,NA)) return ("")
x <- as.data.frame(lapply(df,unclass)) #to accommodate factors()
x[is.na(x)] <- ""
return (x)
}
在您的 server.r (或 UI 模块或需要的地方)
output$ourTable2<-renderTable({format.NAs(data)})
一个通用的例子:
df <- data.frame(A=c(2,4,6,8),B=c(1,NA,9,7),C=c("test",NA,"test1",NA),stringsAsFactors = F)
> format.NAs(df)
A B C
1 2 1 test
2 4
3 6 9 test1
4 8 7
推荐阅读
- arrays - 使用 Guzzle HTTP 发送 JSON HTTP 请求:结果参数与预期不符
- tpm - 实现 TPM2_MakeCredential 的库函数
- javascript - 以“开发”模式构建/打包电子应用程序
- java - 修复 OSGi 设置中 ByteBuddy 和 Vaadin 的类加载问题
- python - 如何使用 Tkinter 销毁从类创建的按钮?
- rxjs - 了解在 rxJS 中对 of(undefined) 的类型更改
- android - Android多SDK项目调试构建
- java - Java中一组数据的排列
- keycloak - Keycloak 用户存储 SPI,未在 keycload 管理控制台中列出用户
- javascript - BrainTree JavaScript Drop In API 和 Kount 设备数据未设置