Reputation: 297
I wonder if there is a way to filter the lastest date of the factor and return the amount that match with it.
Here is my dataframe:
dat <- data.frame(
time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Breakfast","Breakfast"), levels=c("Breakfast")), date=c("2020-01-20","2020-01-21","2020-01-22","2020-02-10","2020-02-11","2020-02-12"),
total_bill = c(12.7557,14.8,17.23,15.7,16.9,13.2)
)
We know that the lastest date is 2020-02-12
and I dont want to write the specific filter like filter(date %in% "2020-02-12")
if the dataframe has been update a day after like 2020-02-13
It will be hard to filter with specific date.
Any help would be much appreciated. Thank you!
Upvotes: 1
Views: 119
Reputation: 887108
An option with subset
subset(transform(dat, date = as.Date(date)), date == max(date))
Upvotes: 1
Reputation: 143
You can use lubridate::ymd
to transform your date
column from character to date, and then use filter
and last
to only select the row that contains the last date in the
dataframe:
library(tidyverse)
library(lubridate)
dat %>%
mutate(date = ymd(date)) %>%
filter(date == last(date))
Upvotes: 2
Reputation: 20463
See ?which.max
to get started:
dat <- data.frame(
time = factor(c("Breakfast","Breakfast","Breakfast","Breakfast","Breakfast","Breakfast"), levels=c("Breakfast")),
date = c("2020-01-20","2020-01-21","2020-01-22","2020-02-10","2020-02-11","2020-02-12"),
total_bill = c(12.7557, 14.8, 17.23, 15.7, 16.9, 13.2)
)
which.max(dat$date)
#> [1] 6
dat[which.max(dat$date), ]
#> time date total_bill
#> 6 Breakfast 2020-02-12 13.2
Alternatively, you can use dplyr
:
library(dplyr)
dat %>%
mutate(date = as.Date(date)) %>%
filter(date == max(date))
#> time date total_bill
#> 1 Breakfast 2020-02-12 13.2
Created on 2020-05-12 by the reprex package (v0.3.0)
Upvotes: 1