我试图循环一个有三个参数的函数,但lapply
和mapply
都没有提供正确的解决方案。这里的目标是基于三个参数(num
,resp
,cdr
)的所有可能组合获得所有可能的结果。如果您看到下面的函数,那么这里的目标是为所有三个等级的num(持有n
和resp
常数)计算cdr
,对于所有三个等级的resp
(持有num
和cdr
常数),以及所有三个等级的cdr
(持有resp
和num
常数)。但正如你从输出中看到的那样,lapply
和mapply
都没有在这里提供正确的答案。
尝试用嵌套的for
循环做这个也没有成功(虽然我在使用循环方面不是那么好,所以如果能得到正确的答案,我会接受基于循环的解决方案)。
最简单的可重复示例:
set.seed(124)
num <- c(10, 20, 30)
resp <- sample(100:200, 3)
cdr <- 3:5
my_fun <- function(num, resp, cdr){
n <- ((num * resp) / cdr)
}
sapply(num, my_fun, resp, cdr)
[,1] [,2] [,3]
[1,] 360 720 1080
[2,] 350 700 1050
[3,] 302 604 906
mapply(my_fun, num, resp, cdr)
[1] 360 700 906
你可以尝试:
df <- expand.grid(data.frame(num, resp, cdr))
with(df, (num * resp) / cdr)
num resp cdr n
1 10 151 3 503.3333
2 20 151 3 1006.6667
3 30 151 3 1510.0000
4 10 176 3 586.6667
5 20 176 3 1173.3333
...
基于purrr / dplyr的解决方案将是:
set.seed(124)
num <- c(10, 20, 30)
resp <- sample(100:200, 3)
cdr <- 3:5
my_fun <- function(num, resp, cdr){
((num * resp) / cdr)
}
args <- list(num = num, resp = resp, cdr = cdr)
args %>%
purrr::cross_df() %>%
dplyr::mutate(res = my_fun(num, resp, cdr))
# gen data
set.seed(124)
num <- c(10, 20, 30)
resp <- sample(100:200, 3)
cdr <- 3:5
# function (written with one input vector)
my_fun <- function(x){
x[1] * x[2] / x[3]
}
# used expand.grid() and apply() to
# eval function on all combos of num, resp, cdr
opts <- expand.grid(num, resp, cdr)
res <- apply(opts, 1, my_fun)
cbind(opts, res)