To find Maximum date

Hi All,
I am new to R programming!
I am trying to find the maximum date, I've tried to use 'max' , but it showing error as 'NA'
I also have tried to convert into a date format, but was not successful. Any workaround?
Thanks

It's hard for us to help without seeing your code. It would be ideal if you could provide a reproducible example (reprex). Please read this guide to see how to create one:

This is the sample code.

Subject_Visits$SVST_DT
[1] "2017-02-13 UTC" "2017-03-13 UTC" "2017-04-10 UTC"
[4] "2017-05-10 UTC" "2017-06-08 UTC" "2017-07-06 UTC"
[7] "2017-08-07 UTC" "2017-09-06 UTC" "2017-09-25 UTC"
max(Subject_Visits$SVST_DT)
[1] NA

You can see above the max date from the above data shows as "NA".

From SO:

Thanks! it helps! one question- if we want to find out max date for each subject as mentioned below:
SubjectA- Date1
SubjectA- Date2
SubjectB-Date1
SubjectB- Date2
Do you have any suggestion?

First group_by(subject), then summarize(maxDate = max(date))

It didn't seems to be working, it is taking the latest date of the column. any other suggestion?

@kmmukesh That is not a reproducible example because we cannot recreate the Subject_Visits object from the code you have supplied. Please read the guide I linked to more carefully as that will increase your chances of getting help from the community.

Since I don't have a sample of your data, I'll make up some of my own to illustrate @phiggins' solution.

library(dplyr, warn.conflicts = FALSE)
library(lubridate, warn.conflicts = FALSE)

df <- tribble(~ subject, ~ date,
              "A", "2017-02-13 UTC",
              "A", "2017-03-13 UTC",
              "A", "2017-04-10 UTC",
              "A", "2017-05-10 UTC",
              "B", "2017-06-08 UTC",
              "B", "2017-07-06 UTC", 
              "B", "2017-08-07 UTC",
              "B", "2017-09-06 UTC",
              "B", "2017-09-25 UTC")

head(df)
#> # A tibble: 6 x 2
#>   subject date          
#>   <chr>   <chr>         
#> 1 A       2017-02-13 UTC
#> 2 A       2017-03-13 UTC
#> 3 A       2017-04-10 UTC
#> 4 A       2017-05-10 UTC
#> 5 B       2017-06-08 UTC
#> 6 B       2017-07-06 UTC

df %>% 
  mutate(date = ymd(date)) %>% # coerce column from character to date
  group_by(subject) %>% 
  summarize(max_date = max(date))
#> # A tibble: 2 x 2
#>   subject max_date  
#>   <chr>   <date>    
#> 1 A       2017-05-10
#> 2 B       2017-09-25

Created on 2020-03-25 by the reprex package (v0.3.0)

2 Likes

Thank you so much! will take care of posing sample data from the next post.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.