How to create a custom column (sortable) in DT::datatable

可紊 提交于 2021-01-28 19:07:37

问题


Let say I have below data-table -

    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))

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.


回答1:


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)
            )
          )
)


来源:https://stackoverflow.com/questions/61669426/how-to-create-a-custom-column-sortable-in-dtdatatable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!