考虑到其中还有其他类型的日期格式,如何将 R 数据框中的日期模式(如“40940”)转换为 01/02/2012?

问题描述 投票:0回答:0

我正在尝试清理这个混乱的数据库。这是链接:https://www.dropbox.com/scl/fi/1crwk2mcag7udiyb5owvl/base_final_informex.xlsx?rlkey=ml66yz7qhr4g1n2ui5tvsfwcv&dl=0

主要问题是变量“inicio”具有各种不同的日期输入,例如:“MAR 23”、“1° Sem 2021”、“OUT/21”、“41365”。 我只想提取日期的年份。我已经成功地使用以下函数做到了这一点:

# Extracting the last two numbers (only the year)
pattern <- "\\b\\d{2}$"

# Function to extract years using regex
extract_years <- function(text, pattern) {
  matches <- regmatches(text, gregexpr(pattern, text))
  years <- sapply(matches, function(x) as.numeric(x))
  return(years)
}

# Use dplyr to extract years from the date_column
informex_clean_2 <- informex_clean |> 
  mutate(ano = extract_years(inicio, pattern))

这对于不像“41365”那样返回 NA 的模式非常有效。

我知道问题在于以某种方式将此数字转换为日期,但我不知道如何做到这一点,因为数据框中的日期不能是数字,甚至不能是正常的日期模式。

嗯,我已经尝试过这个功能了

# Custom function to convert to date if possible
convert_to_date_if_possible <- function(x) {
  if (is.numeric(x)) {
    # If the input is numeric, assume it's a date representation and try to convert it
    x_date <- as.Date(as.numeric(x), origin = "1899-12-30") # Excel's date origin is on 1899-12-30
    if (!is.na(x_date)) {
      # Conversion was successful; return the date object
      return(x_date)
    } else {
      # Conversion failed; return the original value as character
      return(x)
    }
  } else {
    # If the input is not numeric, return the original value as character
    return(x)
  }
}

我期望它能给我想要的东西,但却给了我“41365”模式的 NA 值。

r dplyr lubridate openxlsx
© www.soinside.com 2019 - 2024. All rights reserved.