格式化日期时,rhansontable错误的格式日期显示

时间:2019-02-21 18:35:49

标签: r shiny rhandsontable

我有一个简单的可朗读的闪亮应用程序显示日期,但是日期显示不正确。

    library(rhandsontable)   
    library(magrittr)

    DF_na = data.frame(integer = c(NA, 2:10), 
                               logical = c(NA, rep(TRUE, 9)), 
                               character = c(NA, LETTERS[1:9]),
                               factor = c(NA, factor(letters[1:9])),
                               date = c(NA, seq(from = Sys.Date(), by = "days", 
                                                length.out = 9)),
                               stringsAsFactors = FALSE)

            DF_na$factor_ch = as.character(DF_na$factor)
            DF_na$date_ch = c(NA, as.character(seq(from = Sys.Date(), by = "days", 
                                                   length.out = 9)))

            rhandsontable(DF_na) %>%
 hot_col("date", dateFormat = "DD/MM/YYYY", type = "date")

格式显示错误。日期在我的应用中显示为MM-DD-YY,但是我需要为DD-MM-YY

2 个答案:

答案 0 :(得分:0)

设置R中的日期格式:

x <- format(seq(from = Sys.Date(), by = "days", length.out = 9), "%d/%m/%Y")

DF_na = data.frame(integer = c(NA, 2:10), 
                   logical = c(NA, rep(TRUE, 9)), 
                   character = c(NA, LETTERS[1:9]),
                   factor = c(NA, factor(letters[1:9])),
                   date = as.character(c(NA,x)),
                   stringsAsFactors = FALSE)

rhandsontable(DF_na) %>%
  hot_col("date", dateFormat = "DD/MM/YYYY", type = "date")

enter image description here

答案 1 :(得分:0)

根据此https://github.com/jrowen/rhandsontable/issues/145问题,您必须使用自定义日期格式,您必须执行以下操作:

  1. 将数据框日期列转换为字符
  2. 在hot_col规范中指定dateFormat
  3. 使用hot_to_r读取输入$ table后,从字符串转换回

要修正格式的正确代码清单是:

library(rhandsontable)   
library(magrittr)

DF_na = data.frame(integer = c(NA, 2:10), 
                   logical = c(NA, rep(TRUE, 9)), 
                   character = c(NA, LETTERS[1:9]),
                   factor = c(NA, factor(letters[1:9])),
                   date = c(NA, seq(from = Sys.Date(), by = "days", 
                                    length.out = 9)),
                   stringsAsFactors = FALSE)

DF_na$factor_ch = as.character(DF_na$factor)
DF_na$date_ch = format(as.Date(DF_na$date, origin = "1970-01-01"), "%d/%m/%y")

rhandsontable(DF_na) %>%
  hot_col("date_ch", dateFormat = "DD/MM/YY", type = "date")

enter image description here