簡體   English   中英

從 dataframe 傳遞多個 arguments 到 lapply

[英]Passing multiple arguments to lapply from a dataframe

I'm trying to apply a function to all combinations of 2 arguments using "apply" function in R but I'm getting some errors.

這是我正在做的事情的細分:

我有 2 個 arguments 列表如下:

list1 <- c('a','b','c')
list2 <- c('x','y','z')

我需要將這兩個列表的所有可能組合傳遞給 function,因此我創建了一個 dataframe,如下所示:

combined<-expand.grid(list1 = list1, list2 = list2)

組合的 dataframe 現在包含 9 行數據,其中包含這 2 個列表的所有可能組合。

現在,我有一個 function my_func() 接受 2 個 arguments 例如 my_func('a','x') 並生成一些 output。

我想將此 function 應用於上面創建的組合 dataframe 的所有這 9 行,所以我使用 apply function 如下:

apply(x,resp_rate)

運行此代碼會生成以下錯誤。

match.fun(FUN) 中的錯誤:缺少參數“FUN”,沒有默認值

如果有人能告訴我我做錯了什么,我將不勝感激。

在第二個參數中使用apply您需要傳遞MARGIN以指定是否要按行 (1) 或按列 (2) 應用 function。 此外,您還需要在此處使用匿名 function,因為您的 function 接受兩個單獨的 arguments。

apply(combined, 1, function(x) my_func(x[1], x[2]))

暫無
暫無

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

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