Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R: Max/Min date returning NA

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading