问题
I have a dataset with a text field which I would like to display using the function datatable from the package DT. I would also like to (1) format that text field so that the line breaks are displayed and emphasis is placed on certain chunks of text; and (2) vertically align the remaining fields so that their values are pushed to the top.
Consider the below example:
library(DT)
L <- 10
datatable(
data.frame(
var1 = sapply(1:L, function(x)
paste("<X>",paste0(x,
letters,
LETTERS,
"\n",
collapse=" "))),
var2 = round(rnorm(L),2)
)
)
As you can see, the output ignores \n. I would also like to make <X> bold. I've tried using HTML tags such as <br> but nothing seems to work as the text inside var1 is escaped. Unescaping it (which can be achieved via datatable options) is not a good idea as the (actual) text contains special characters. I would also like the values of var2 to be pushed to the top.
Just in case it make a difference, I would like to use the outputs in a Shiny web-app.
Does anyone have any suggestions on how to achieve what I'm looking for?
Many thanks in advance.
回答1:
To implement the line break in the DT cells you need to use <br/> instead of \n and escape(it will be read as HTML) the column with the escape argument.
To change the alignment of a value in a cell you can use the columnDefs argument within the options of datatable function. The problem is that you only can align horizontal.( left, right and center) With the rowCallback function I can manually set every value in the second column to top alignment. But this is not an ideal solution.
library(DT)
L <- 10
dataset <- data.frame(
var1 = sapply(1:L, function(x)
paste("<X>",paste0(x,
letters,
LETTERS,
"<br/>",
collapse=" "))),
var2 = round(rnorm(L),2)
)
datatable(dataset, escape = 1,
options = list(
columnDefs = list(list(className = 'dt-center', targets = 2)),
rowCallback=JS(paste0("function(row, dataset) {var value=dataset[2]; if (value!==null) $(this.api().cell(row,2).node()).css({'vertical-align': 'text-top'});}"))
)
)
来源:https://stackoverflow.com/questions/38348629/r-dt-datatable-format-text-field-and-vertically-align-another-field