gpt4 book ai didi

R:将参数传递给外部()

转载 作者:行者123 更新时间:2023-12-01 07:54:52 27 4
gpt4 key购买 nike

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)

有什么不见了 ?

最佳答案

我建议使用 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 排序上类。

关于R:将参数传递给外部(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250098/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com