![](/img/trans.png)
[英]Is there any way to combine two different functions to one function in R?
[英]Passing results of different functions to a function the R way
我有多個函數,想將其結果傳遞給另一個函數(多個函數調用)。 這樣做的R方向是什么?
防爆。
x = function_x() { ... return vector}
y = function_y() { ... return vector}
z = function_z() { ... return vector}
func_abc(x)
func_abc(y)
func_abc(z)
目前,我正在創建函數向量,並使用lapply在多個函數調用中傳遞其結果:
function_x() { ... return vector}
function_y() { ... return vector}
function_z() { ... return vector}
my_vectors <- c(function_x(), function_y(), function_z())
lapply(my_vectors, function_abc(v) {
... do something on v
})
更具體地說,function_x,_y和_z返回向量。 我想對其返回的向量進行過濾,這就是我的function_abc。 然后合並它們。
試試這個例子:
#set seed to make it reproducible
set.seed(1234)
#define functions
function_x <- function(){ sample(1) }
function_y <- function(){ sample(2) }
function_z <- function(){ sample(3) }
#get function results into a list
myList <- list(function_x(), function_y(), function_z())
#loop through the list and row bind
do.call(rbind,
lapply(myList, function(v) {
#some calculations, result is a data.frame
res <- cbind.data.frame(input=v, calculation=v*2)
return(res)
}))
#result
# input calculation
#1 1 2
#2 2 4
#3 1 2
#4 2 4
#5 3 6
#6 1 2
上面可以簡化如下:
#define function for calculations
function_abc <- function(x){ x * 2 }
#loop
unlist(lapply(list(function_x(), function_y(), function_z()), function_abc))
#result
# [1] 2 4 2 4 6 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.