Anshul S
Anshul S

Reputation: 281

Max Date based on Date & TimeStamp

Can someone help for the below issue in R

DF1:

Item   Date
A      2020-04-08 03:36:28
B      2020-04-08 05:16:28

Output:

Item   Date
B      2020-04-08 05:16:28

Here, maximum date along with timestamp should be selected.

Upvotes: 1

Views: 130

Answers (2)

akrun
akrun

Reputation: 887991

In base R, we can do

DF1[which.max(DF1$Date),, drop = FALSE]

Upvotes: 1

user63230
user63230

Reputation: 4708

perhaps this works:

library(tidyverse)
now <- Sys.time()
#"2020-04-16 18:04:30 BST"
now2 <- as.POSIXlt(now)
now <- Sys.time()
now3 <- as.POSIXlt(now)
# [1] "2020-04-16 18:06:23 BST"
df <- data.frame(group = c("a", "b"), 
                 time = c(now2, now3))
str(df)

df %>% 
  slice(which.max(time)) 
#   group                time
# 1     b 2020-04-16 18:06:23

OR if you have character variable, convert first with as.POSIXct

df <- data.frame(group = c("a", "b"), 
                 time = c("2020-04-08 03:36:28", "2020-04-08 05:16:28"))
df <- df %>% 
  mutate(time2 = as.POSIXct(time)) %>% 
  select(-time) 

df %>% 
  slice(which.max(time2)) 
#   group               time2
# 1     b 2020-04-08 05:16:28

Upvotes: 1

Related Questions