【问题标题】:I get NA using as.Date in r我在 r 中使用 as.Date 得到 NA
【发布时间】:2022-12-05 15:16:33
【问题描述】:

当我在 r 中使用“as.Date”命令时,它返回 Na 作为结果,我尝试了不同的方法,比如将它转换为 POSIXt 格式,但它不起作用

#this is the format i need it to read
format(Sys.Date(), "%B de %Y")

# this is an example of what i need
date="noviembre de 2022"
class(date)

#this is what i tried
date2 <- strptime(date, format = "%B de %Y")
class(date2)
date3 <- as.Date(date2,format="%B de %Y")
class(date3)
date3

这就是我得到的 na as result

我想要类似的东西

navidad2021=as.Date("25 Diciembre 2021",format="%d %B %Y")
navidad2021
[1] "2021-12-25"

但在这种格式

format(Sys.Date(), "%B de %Y")
[1] "December de 2022"

非常感谢你的帮助

【问题讨论】:

    标签: r na as.date


    【解决方案1】:

    您遇到的问题似乎与您在 strptimeas.Date 函数中使用的日期格式字符串有关。在您的示例中,您使用格式字符串 "%B de %Y",它指定月份为全文形式(例如“noviembre”),后跟字符串“de”和年份。但是,此格式字符串与您尝试解析的日期字符串的格式不匹配,格式为 "noviembre de 2022"

    要解决此问题,您需要使用与日期字符串格式匹配的格式字符串。在这种情况下,您可以使用以下格式字符串:"%B de %Y"。这是一个如何做到这一点的例子:

    # Define the date string
    date <- "noviembre de 2022"
    
    # Parse the date string using the correct format string
    date2 <- strptime(date, format = "%B de %Y")
    
    # Convert the date to a Date object
    date3 <- as.Date(date2,format="%B de %Y")
    
    # Print the date
    date3
    

    这应该以正确的格式返回日期,以全文形式返回月份和年份。然后,您可以使用 format 函数将日期转换为所需的格式,如您的示例所示。

    【讨论】:

      【解决方案2】:

      日期是 R 中的内置数据类型之一。当您打印日期时,它使用内置的 print.Date 函数将其显示为 YYYY-MM-DD。您还可以创建一个字符串(正如您所做的那样)以使用另一种格式显示日期,但是它将不再是您可以操作的日期。

      如果您希望它以不同的方式打印,您可以在您的系统上覆盖print.Date

      print.Date <- function (x, max = NULL, ...) 
      {
        if (is.null(max)) 
          max <- getOption("max.print", 9999L)
        if (max < length(x)) {
          print(format(x[seq_len(max)]), max = max + 1, ...)
          cat(" [ reached 'max' / getOption("max.print") -- omitted", 
              length(x) - max, "entries ]
      ")
        }
        else if (length(x)) 
          print(format(x, "%B de %Y"), max = max, ...)
        else cat(class(x)[1L], "of length 0
      ")
        invisible(x)
      }
      
      as.Date("2021-12-25")
      [1] "December de 2021"
      as.Date("2021-12-25") + 7
      [1] "January de 2022"
      

      但是,这对其他人不起作用,除非您也覆盖他们的print.Date,这是一种错误的形式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多