簡體   English   中英

在應用中將多個 arguments 傳遞給 function

[英]Passing multiple arguments to a function in apply

我在將多個 arguments apply function 時遇到問題。 To be specific i have a boolean function of N arguments, from a1 to aN , and i want to compute the truth table for a given function. 這是一個示例,大多數 function 的 3 個 arguments

majority <- function(a1, a2, a3) {
  (a1 & a2) | (a2 & a3) | (a1 & a3)
}

我還生成了一個表,其中包含 function 的所有可能輸入

truth <- matrix(nrow = 2^3, ncol = 3+1)
for (i in 1:(2^3)) {
  truth[i, -(3+1)] <- rev(as.numeric(intToBits(i-1)))[-(1:(32-3))]
  # a bit flimsy but thats not the point
}

然后我想用相應輸入行中給定 function 的值填充最后一列,但是代碼...

apply(truth[, -(3+1)], 1, majority)

...返回錯誤: Error in FUN(newX[, i], ...): argument "a2" is missing, with no default

如何使用應用 function 將多個 arguments 傳遞給 function? 我知道您可以使用do.call function 將 arguments 列表傳遞給 function,但這似乎在應用程序中不起作用。

任何幫助,將不勝感激。

您可以在這里使用 apply function :

apply(truth[, -(3+1)], 1, function(x) majority(a1 = x[1], a2 = x[2], a3 = x[3]))

在上面,將x視為truth矩陣的給定行。 我們傳遞給您的多數 function a1 = x[1] , a2 = x[2] , a3 = x[3] (行中的三個元素x

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM