如何在R中复制函数并获得最后的结果?



我有一个对DataFrame进行一些更改的函数。我想重复这个函数N次,得到最终的Dataframe。我怎样才能做到这一点?

目前我的功能是:

DF// Dataframe
fun <- function(){
// For some rows only
DF_processed <- t(apply(DF[rows, ], 1, sum))

// Add to original DF
DF[rows,] <- DF_processed

return DF
}

我想运行这个函数3次,得到最后的DF。我试过了:

lapply(seq_len(3), function(x) fun())

但是我不能得到结果保存在我原来的DF

Using loop

首先,与其在全局环境中修改对象,不如将对象作为参数传递给函数,并让函数返回修改后的对象。一般来说,你应该使用一个像

这样的函数
fun <- function(x) {
# do some processing on x - this will create a local copy of it...
# now return the modified object (this should not change
# the original object). Also note that 'return' is a function
# (like everything in R), so you need to use parentheses.
return(x)
}

然后你可以这样做:

# define x
x <- ...
for (i in seq_len(3)) {
x <- fun(x)
}

请注意,这将改变x所指向的对象,因为for循环是在全局环境中运行的。

使用减少

你可以使用Reduce函数(参见?Reduce)来应用一个函数列表——在这种情况下,列表中的所有函数都是相同的函数,但这不是必需的——到一个"开始值"。这实际上是一个组合函数的方法:

# The starting value
x <- 2
# This is the function we want to apply
fun <- function(x) x*x
# The following is equivalent to "fun_list <- list(fun, fun, fun)", but more flexible
fun_list <-rep(list(fun), 3 )
fun_call <- function(f, ...) f(...)
res <- Reduce(fun_call, fun_list, x, right = TRUE)

现在res是最终结果。

这相当于简单形式

res <- fun(fun(fun(x)))

是另一种方式,但不太灵活。

最新更新