0

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
Michael
  • 221
  • 1
  • 8
  • 5
    Did you just want `... %>% mutate(min = min(amt))` ? – thelatemail Jun 29 '22 at 01:29
  • ah, so simple! I was overthinking it! Thank you. – Michael Jun 29 '22 at 01:32
  • 2
    You're trying to do two different things. `slice` returns subsets of the data frame. You could also have used `slice_min()` instead of `slice(which.min(...))`. As suggested, you just need `min()` in the second case. Unrelated: I'd avoid using variable names that could be confused with function names (data, min). – neilfws Jun 29 '22 at 01:35
  • If you were to use `which.min`, then you would want to use that to subset the actual `amt`, and return that minimum amount for each group. So, `... %>% mutate(min = amt[which.min(amt)])`. This is more handy when you need to use the minimum from one column to return a value from another column. In this case, much better to use what @thelatemail suggests. – AndrewGB Jun 29 '22 at 03:41

0 Answers0