set.seed(8)
data <-
data.frame(A=rnorm(10),
B=rnorm(10))
fun <- function(df,x,y){
require(dplyr)
res <-
filter(df,A<x,B>y) %>%
nrow()
return(res)
}
This work for single values of x and y:
fun(x=1,y=0,df=data)
I would like to do use outer() (or similar) to do combinations of an x and y but cannot figure out how to pass the df argument. It seems to be the same issue as in here:
Using outer() with a multivariable function.
But passing df through ...
does not work:
outer(x=c(0,2),y=c(0,2),fun,df=data)
What is missing ?
I'd suggest using cut
:
# borrowing the @Colonel's example:
x = c(0,1,2)
y = c(-1,0,2)
library(magrittr)
data %<>% mutate(
Ag = cut(A,c(-Inf,x,Inf)),
Bg = cut(B,c(-Inf,y,Inf))
)
with(data, table(Ag,Bg))
# Bg
# Ag (-Inf,-1] (-1,0] (0,2] (2, Inf]
# (-Inf,0] 1 4 3 0
# (0,1] 0 0 2 0
# (1,2] 0 0 0 0
# (2, Inf] 0 0 0 0
This may not match the inequalities the OP is after, but I suspect some variation would do the trick. Note that x
and y
have to be sorted for cut
to work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With