Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: pass args to outer()

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 ?

like image 869
user3375672 Avatar asked Sep 12 '25 12:09

user3375672


1 Answers

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.

like image 74
Frank Avatar answered Sep 15 '25 02:09

Frank