igroffman commited on
Commit
9cfd949
·
verified ·
1 Parent(s): 170ac81

Update app.R

Browse files
Files changed (1) hide show
  1. app.R +30 -3
app.R CHANGED
@@ -61,8 +61,20 @@ pitch_colors <- c(
61
 
62
  # Function to convert date formats
63
  convert_date_format <- function(date_string, output_format = "yyyy") {
64
- if (is.na(date_string) || date_string == "") {
65
- return(NA)
 
 
 
 
 
 
 
 
 
 
 
 
66
  }
67
 
68
  date_string <- as.character(date_string)
@@ -105,7 +117,22 @@ convert_date_columns <- function(df, output_format = "yyyy") {
105
 
106
  for (col in date_columns) {
107
  if (col %in% names(df)) {
108
- df[[col]] <- sapply(df[[col]], function(x) convert_date_format(x, output_format), USE.NAMES = FALSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  }
110
  }
111
 
 
61
 
62
  # Function to convert date formats
63
  convert_date_format <- function(date_string, output_format = "yyyy") {
64
+ # Handle NULL, zero-length, or NA inputs safely
65
+ if (is.null(date_string) || length(date_string) == 0) return(NA_character_)
66
+ if (inherits(date_string, "Date") || inherits(date_string, "POSIXct")) {
67
+ # Already a proper date object (common from parquet) — format directly
68
+ if (is.na(date_string)) return(NA_character_)
69
+ parsed_date <- as.Date(date_string)
70
+ if (output_format == "mdyy") {
71
+ return(gsub("/0", "/", gsub("^0", "", format(parsed_date, "%m/%d/%y"))))
72
+ } else {
73
+ return(format(parsed_date, "%Y-%m-%d"))
74
+ }
75
+ }
76
+ if (is.na(date_string) || identical(as.character(date_string), "")) {
77
+ return(NA_character_)
78
  }
79
 
80
  date_string <- as.character(date_string)
 
117
 
118
  for (col in date_columns) {
119
  if (col %in% names(df)) {
120
+ col_data <- df[[col]]
121
+
122
+ # If the column is already a Date or POSIXct (common from parquet),
123
+ # format it directly instead of running through the regex-based parser
124
+ if (inherits(col_data, "Date") || inherits(col_data, "POSIXct")) {
125
+ if (output_format == "mdyy") {
126
+ df[[col]] <- ifelse(is.na(col_data), NA_character_,
127
+ gsub("/0", "/", gsub("^0", "", format(as.Date(col_data), "%m/%d/%y"))))
128
+ } else {
129
+ df[[col]] <- ifelse(is.na(col_data), NA_character_,
130
+ format(as.Date(col_data), "%Y-%m-%d"))
131
+ }
132
+ } else {
133
+ # Character column — use the string-parsing path
134
+ df[[col]] <- sapply(df[[col]], function(x) convert_date_format(x, output_format), USE.NAMES = FALSE)
135
+ }
136
  }
137
  }
138