循环遍历有三个参数的函数,mapply / sapply / for循环不起作用?

问题描述 投票:1回答:3

我试图循环一个有三个参数的函数,但lapplymapply都没有提供正确的解决方案。这里的目标是基于三个参数(numrespcdr)的所有可能组合获得所有可能的结果。如果您看到下面的函数,那么这里的目标是为所有三个等级的num(持有nresp常数)计算cdr,对于所有三个等级的resp(持有numcdr常数),以及所有三个等级的cdr(持有respnum常数)。但正如你从输出中看到的那样,lapplymapply都没有在这里提供正确的答案。

尝试用嵌套的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
r lapply sapply mapply
3个回答
4
投票

你可以尝试:

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
...

2
投票

基于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))

0
投票
# 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)
© www.soinside.com 2019 - 2024. All rights reserved.