RenaudG
RenaudG

Reputation: 13

How to use something like tapply but keeping other columns in R

Let's say I have this data frame :

 Date Value1 Value2
01-01   13.6     20
01-01   25.4     25
01-01   49.5     18
02-01   12.2     22
02-01   28.2     35
02-01   42.2     26

and I would like to keep only the lines in this table that have the minimum "Value1" for each "Date", so in this case :

 Date Value1 Value2
01-01   13.6     20
02-01   12.2     22

I would use tapply(df$Value1, df$Date, min) if there was no "Value2" column, but I would like to keep this column in my summarized table. Do you have something simple to suggest ? I found different similar topics but never understood how to adapt in my case.

Upvotes: 1

Views: 67

Answers (1)

akrun
akrun

Reputation: 887301

We can slice after grouping by 'Date'

library(dplyr)
df1 %>%
   group_by(Date) %>%
   slice(which.min(Value1))

Or with filter

df1 %>%
  group_by(Date) %>%
  filter(Value1 == min(Value1))

In base R, this can be one with ave

df1[with(df1, Value1 == ave(Value1, Date, FUN = min)),]

Upvotes: 3

Related Questions