如果列名不存在,为什么 DT 包中的 formatCurrency() 会出错?

Why formatCurrency() in DT package gives error if the column name is not present?

假设我在一个闪亮的应用程序中使用这段代码,其中的列使用闪亮的输入进行过滤:

library(magrittr)
library(DT) # version 0.18

data_viz <- data.frame(Item = c("Milk", "Bread", "Flour"), Quantity = c(2,3,4), Price = c(4,5,6)) # Original data

data_table_viz <- data_viz[, c("Item", "Quantity")] # Filtering columns on the go using Shiny app input 

datatable(data = data_table_viz) %>% formatCurrency(c("Price")) # Throws error: You specified the columns: Price, but the column names of the data are  , Item, Quantity

它抛出错误: name2int(name, names, rownames) 错误: 您指定了列:Price,但数据的列名是 , Item, Quantity

该错误是可以理解的,但我想避免此错误,而是忽略“价格”列并呈现剩余数据。下面是一个解决方法:

datatable(data = data_table_viz) %>% formatCurrency(c("Price")[c("Price") %in% colnames(data_table_viz)])

它曾经在 DT 包版本 0.13 之前工作,但之后就停止工作了。

它现在抛出错误: mapply(FUN = f, ..., SIMPLIFY = FALSE) 错误: 零长度输入不能与非零长度输入混合

有没有人有解决这个问题的其他方法,或者我应该继续使用旧版本的 DT 包吗?

您可以添加一个 if 条件来检查该列是否存在。

library(magrittr)
library(DT)

dt <- datatable(data = data_table_viz) 
if('Price' %in% colnames(data_table_viz)) dt <- dt %>% formatCurrency("Price")