简体   繁体   English

通过R方式将不同函数的结果传递给函数

[英]Passing results of different functions to a function the R way

I have multiple functions and want to pass their results to another function (multiple function calls). 我有多个函数,想将其结果传递给另一个函数(多个函数调用)。 What is the R-way of doing this? 这样做的R方向是什么?

Ex. 防爆。

x = function_x() { ... return vector}
y = function_y() { ... return vector}
z = function_z() { ... return vector}
func_abc(x)
func_abc(y)
func_abc(z)

Currently I am creating a vector of functions and using lapply to pass their results on multiple function calls: 目前,我正在创建函数向量,并使用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
})

To be more specific, function_x, _y, and _z returns vectors. 更具体地说,function_x,_y和_z返回向量。 I want to do some filtering for their returned vectors which is my function_abc. 我想对其返回的向量进行过滤,这就是我的function_abc。 Then combine them. 然后合并它们。

Try this example: 试试这个例子:

#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

Above can be simplified as below: 上面可以简化如下:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM