Menno Van Dijk
Menno Van Dijk

Reputation: 903

Dplyr pipe operation obtaining minimum

When trying to combine R pipe operations with obtaining a minimum, I came across this issue. I would expect this to work but it doesn't. Can anyone explain to me why this is the case, and how to fix it?

df <- data.frame(ID = c(1,2,3,4),
                 Name = c("Name1", "Name1", "Name2", "Name3"),
                 Value = c(10, 14, 13, 1))

df <- df %>%
        filter(grepl("name1", Name, ignore.case = TRUE)) %>%
        min(Value) 

Error in function_list[[k]](value) : object 'Value' not found

Upvotes: 1

Views: 671

Answers (1)

akrun
akrun

Reputation: 886938

We can pull the column 'Value' as a vector and get the min

library(dplyr)
df %>%
       filter(grepl("name1", Name, ignore.case = TRUE)) %>% 
       pull(Value) %>% 
       min

Or use summarise

 df %>%
       filter(grepl("name1", Name, ignore.case = TRUE)) %>%
       summarise(Value = min(Value))

The reason is that the output from the %>% is the full dataset, we need to extract the column with $ or [[

df %>%
    filter(grepl("name1", Name, ignore.case = TRUE)) %>%
     {min(.$Value)}
#[1] 10

Upvotes: 2

Related Questions