I have the following data frame:
id <- c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5)
amt <- c(1.5,3,5,10,4,6,3,2.2,7,8,16,2,3.4,1.4,5)
data <- data.frame(id, amt)
I am trying to add a column for the min value of amt
by id
to the data frame.
I can find the min value like so:
data %>%
group_by(id) %>%
slice(which.min(amt))
But when I try to add a column like this:
data %>%
group_by(id) %>%
mutate(min = slice(which.min(amt)))
I get:
Error in `mutate()`:
! Problem while computing `min = slice(which.min(amt))`.
ℹ The error occurred in group 1: id = 1.
Caused by error in `UseMethod()`:
! no applicable method for 'slice' applied to an object of class "c('integer', 'numeric')"
Desired output:
id amt min
1 1.5 1.5
1 3 1.5
1 5 1.5
2 10 4
2 4 4
2 6 4
3 3 2.2
3 2.2 2.2
3 7 2.2
4 8 2
4 16 2
4 2 2
5 3.4 1.4
5 1.4 1.4
5 5 1.4