pmin() with dplyr in R

Viewed 1023

This is a fairly simple question. For some reason the pmin() function does not work when piped with a dataframe. See below:

library(dplyr)
data(mtcars)
pmin(mtcars$am, mtcars$gear)
1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1
mtcars %>% pmin(am, gear)
Error in pmin(., am, gear): object 'am' not found
Traceback:

1. mtcars %>% select(am, gear) %>% pmin(am, gear)
2. withVisible(eval(quote(`_fseq`(`_lhs`)), env, env))
3. eval(quote(`_fseq`(`_lhs`)), env, env)
4. eval(quote(`_fseq`(`_lhs`)), env, env)
5. `_fseq`(`_lhs`)
6. freduce(value, `_function_list`)
7. withVisible(function_list[[k]](value))
8. function_list[[k]](value)
9. pmin(., am, gear)

What I am missing? Your advice will be appreciated.

1 Answers

Where your going wrong is that the pipe operator passes the data frame as the first argument. So your trying to run pmin(select(mtcars,am, gear), am, gear).

As Nate's comment suggests, mtcars%>%with(pmin(am, gear)) does what you want.

Also, a slight modification on Marco's comment. mtcars%>%transmute(pmin(am,gear))%>%pull

Related