【问题标题】:R: pass args to outer()R:将参数传递给外部()
【发布时间】:2015-07-06 15:44:47
【问题描述】:
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)
}

这适用于 x 和 y 的单个值:

fun(x=1,y=0,df=data)

我想使用 outer() (或类似的)来组合 x 和 y 但不知道如何传递 df 参数。这似乎与此处的问题相同: Using outer() with a multivariable function。 但是通过... 传递df 不起作用:

outer(x=c(0,2),y=c(0,2),fun,df=data)

缺少什么?

【问题讨论】:

  • fun 的前两个参数必须是您的 xy 并且如果您想使用 @987654329,则必须针对这些参数进行矢量化@.
  • @Roland:你能否详细说明...'必须矢量化'
  • 矢量化(yourFucntion...., vec=c("x", "y"))
  • @Legalizelt:我没明白对不起

标签: r combinations dplyr


【解决方案1】:

我建议使用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

这可能与 OP 所追求的不等式不匹配,但我怀疑一些变化可以解决问题。请注意,xy 必须进行排序,cut 才能工作。

【讨论】:

    【解决方案2】:

    向量化参数意味着您的函数可以将向量作为参数(!)。正如 cmets 中的@Roland 所述,您的函数需要专门设置为与outer 一起使用。所以前两个参数应该向量化。这意味着您可以为xy 传递一个参数向量,并且将在这两个值的每个值上调用该函数。您可以使用Vectorize 函数轻松完成此操作。

    fun <- Vectorize(function(x, y, df){
      require(dplyr)
      res <- 
        filter(df,A<x,B>y) %>%
        nrow()
      return(res)
    }, vectorize.args=c("x", "y"))
    
    
    outer(c(0,1,2), c(-1,0,2), fun, df=data)
    
    #      [,1] [,2] [,3]
    # [1,]    7    3    0
    # [2,]    9    5    0
    # [3,]    9    5    0
    

    【讨论】:

    • 并在结果中获得暗名:outer(setNames(x,x), setNames(y,y), fun, df=data)
    • 很好,vec 是 Vectorize 的 vectorize.args 参数吗?
    • @user3375672 是的,R 函数将通过部分匹配来匹配参数
    【解决方案3】:

    您可以使用Currymapply

    library(functional)
    
    df = expand.grid(c(1,2,0),c(-1,2,0))
    
    mapply(Curry(fun, df=data), df[,1],df[,2])
    #[1] 9 9 7 0 0 0 5 5 3
    

    【讨论】:

    • mapply 不是我想要的:我需要 x 和 y 的所有组合,即 3x3 矩阵(9 个结果)
    • 在这种情况下,只需给 mapply 正确的参数 ;)
    • 有人吗?好像快到了!
    • 也许你想把结果放在一个矩阵中(就像outer 那样)?
    • 是的!但我相信外部会这样做 - 如果正确地放在@LegalizeIt的答案中
    猜你喜欢
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    • 2016-02-29
    • 2020-02-20
    相关资源
    最近更新 更多