Let’s say I have a dataframe of Name
and value
, is there any ways to extract BOTH minimum and maximum values within Name
in a single function?
set.seed(1)
df <- tibble(Name = rep(LETTERS[1:3], each = 3), Value = sample(1:100, 9))
# A tibble: 9 x 2
Name Value
<chr> <int>
1 A 27
2 A 37
3 A 57
4 B 89
5 B 20
6 B 86
7 C 97
8 C 62
9 C 58
Thanks in advance!
>Solution :
You can use range
to get max
and min
value and use it in summarise
to get different rows for each Name
.
library(dplyr)
df %>%
group_by(Name) %>%
summarise(Value = range(Value), .groups = "drop")
# Name Value
# <chr> <int>
#1 A 27
#2 A 57
#3 B 20
#4 B 89
#5 C 58
#6 C 97
If you have large dataset using data.table
might be faster.
library(data.table)
setDT(df)[, .(Value = range(Value)), Name]