本文介绍了如何在DT :: datatable中创建自定义列(可排序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在数据表-

    library(DT)
     d = data.frame(
      names = rownames(mtcars),
      date = as.Date('2015-03-23') + 1:32,
      time = as.POSIXct('2015-03-23 12:00:00', tz = 'UTC') + (1:32) * 5000,
      stringsAsFactors = FALSE
    )

    datatable(d, filter = 'bottom', options = list(pageLength = 5))

现在,我想通过组合 date + time + some-other-string 作为 date_time 数据表中创建新列.此新列 date_time 应该只能基于 date 部分(而不是 time 部分或 string 部分)进行排序.我还想为 date 部分和 time 部分提供不同的颜色.

Now I want to create a new column in the data-table by combining date+time+some-other-string as date_time. This new column date_time should be sortable based only on date part (not the time part nor string part). I also want to give different colour for date part and time part.

有什么办法可以做到这一点?

Is there any way to achieve this?

任何指针都将受到高度赞赏.

Any pointer will be highly appreciated.

推荐答案

要根据第二列对第四列进行排序:

To sort the fourth column according to the second column:

library(DT)

render <- JS(
  "function(data, type, row, meta){",
  "  if(type === 'sort' || type === 'type'){",
  "    return row[2];",
  "  } else {",
  "    return data;",
  "  }",
  "}"
)

d = data.frame(
  names = rownames(mtcars),
  date = as.Date('2015-03-23') + 1:32,
  time = as.POSIXct('2015-03-23 12:00:00', tz = 'UTC') + (1:32) * 5000,
  otherColumn = mtcars$mpg,
  stringsAsFactors = FALSE
)

datatable(d, filter = 'bottom',
          options = list(
            pageLength = 5,
            columnDefs = list(
              list(targets = 4, render = render)
            )
          )
)

对于颜色,您可以执行以下操作:

For the colors, you can do:

render <- JS(
  "function(data, type, row, meta){",
  "  if(type === 'sort' || type === 'type'){",
  "    return row[2];",
  "  } else if(type === 'display'){",
  "    var date = '<span style=\"color:red;\">' + row[2] + ' </span>';",
  "    var time = '<span style=\"color:blue;\">' + row[3] + ' </span>';",
  "    var other = '<span style=\"color:green;\">' + data + '</span>';",
  "    return date + time + other;",
  "  } else {",
  "    return data;",
  "  }",
  "}"
)

d = data.frame(
  names = rownames(mtcars),
  date = as.Date('2015-03-23') + 1:32,
  time = as.POSIXct('2015-03-23 12:00:00', tz = 'UTC') + (1:32) * 5000,
  otherColumn = stringi::stri_rand_strings(32, 3),
  stringsAsFactors = FALSE
)

datatable(d, filter = 'bottom',
          options = list(
            pageLength = 5,
            columnDefs = list(
              list(targets = 4, render = render)
            )
          )
)

这篇关于如何在DT :: datatable中创建自定义列(可排序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 19:53