Home > front end >  R: Max/Min date returning NA
R: Max/Min date returning NA

Time:02-08

I have a year column & month column. I paste them into a new column and achieve the format of "yyyy-mm-dd". All "dd" are "01". I tried converting this column using "as.date", "as.POSIXct". However when I tried to find Max & Min, the result is NA. Below is the code I ran.

##Add 0 as leading numeric for single numeric months
df$new_month_col <- ifelse(nchar(df$month) < 2,
paste0("0",df$month,sep = ""), df$month)
            
##Paste as new column "date"   
df$date <- paste(df$year,"-",df$new_month_col,"-01",sep = "")
        
##Converting data type
df$date<- as.date(df$date, format = "%Y-%m-%d")
df$date<- as.POSIXct(df$date, format = "%Y-%m-%d")
    
max(df$date)
[1] NA

CodePudding user response:

Something like this?

library(tidyverse)

df <- tibble(date = c("2022-1", "2021-10", "2020-9", NA))
df
#> # A tibble: 4 x 1
#>   date   
#>   <chr>  
#> 1 2022-1 
#> 2 2021-10
#> 3 2020-9 
#> 4 <NA>

df <- mutate(df, date = date %>% paste0("-01") %>% as.Date())
df
#> # A tibble: 4 x 1
#>   date      
#>   <date>    
#> 1 2022-01-01
#> 2 2021-10-01
#> 3 2020-09-01
#> 4 NA

min(df$date, na.rm = TRUE)
#> [1] "2020-09-01"
max(df$date, na.rm = TRUE)
#> [1] "2022-01-01"

Created on 2022-02-08 by the reprex package (v2.0.1)

  •  Tags:  
  • Related