RitaM
RitaM

Reputation: 143

dplyr: max and min between a row and a specific value

I'm trying to create the code that results in the max value between a given row and a specific value, but I don't know how to do it. I've seen some suggestions here, but they are only applicable to several values ​​of the row

Here is a simple example, of my expected result. I want the max value between the "Start" and 19:00:00 (I´m using hms)

Type | Start    | max_value_between
<chr>| <hms>    |   <hms>
 A   | 19:30:00 |  19:30:00
 B   | 18:45:00 |  19:00:00

thanks in advance

Upvotes: 0

Views: 537

Answers (3)

Zaw
Zaw

Reputation: 1474

library(tidyverse)
library(hms)

data <- tribble(
  ~Type, ~Start, 
  "A", "19:30:00",
  "B", "18:45:00"
) %>% 
  mutate(Start = hms::as_hms(Start))

data %>% 
  mutate(
    max_value = if_else(Start > as_hms("19:00:00"), Start, as_hms("19:00:00"))
  )


# # A tibble: 2 x 3
#   Type  Start  max_value
#   <chr> <time> <time>   
# 1 A     19:30  19:30    
# 2 B     18:45  19:00 

Upvotes: 0

akrun
akrun

Reputation: 887991

We can also use

library(dplyr)
my_data %>%
   rowwise %>%
   mutate(max_value_between = max(Start, "19:00:00")) %>%
   ungroup

Upvotes: 1

Cettt
Cettt

Reputation: 11981

You can use pmax:

mydata$max_value_between <- pmax(mydata$Start, '19:00:00')

Upvotes: 1

Related Questions