admin管理员组文章数量:1277257
I am trying to write a function where I apply the same set of functions to a list.
Currently I got this approach to work but it seems very clumsy and I wonder if and how it can be improved:
t1 <- lapply(mylist,
FUN = myfunc1)
t2 <- lapply(t1,
FUN = as.data.frame)
t3 <- lapply(t2,
FUN = t)
t4 <- lapply(t3,
FUN = myfunc2)
So I first need to extract objects from a list, turn them into data frames, then transpose them and then finally apply the real function.
I am trying to write a function where I apply the same set of functions to a list.
Currently I got this approach to work but it seems very clumsy and I wonder if and how it can be improved:
t1 <- lapply(mylist,
FUN = myfunc1)
t2 <- lapply(t1,
FUN = as.data.frame)
t3 <- lapply(t2,
FUN = t)
t4 <- lapply(t3,
FUN = myfunc2)
So I first need to extract objects from a list, turn them into data frames, then transpose them and then finally apply the real function.
Share Improve this question asked Feb 24 at 12:40 keep_swimmingkeep_swimming 331 silver badge6 bronze badges 4 |2 Answers
Reset to default 1As mentioned in the comments, you can use one instance of lapply
to do all of this, you just need to use a custom function in the FUN
argument. You can do so with function
or \
:
lapply(mylist, FUN = function(x) myfunc2(t(as.data.frame(myfunc1(x)))))
Because nested functions can be a bit hard to read, you can use a pipe to decompose your sequence of functions without changing the order of compilation:
lapply(mylist, FUN = \(x){
x |>
myfunc1() |>
as.data.frame() |>
t() |>
myfunc2()
})
1) We can use Reduce
on a list of functions:
L <- as.list(1:3)
Reduce(lapply, list(sqrt, exp), init = L)
2) Also
lapply(L, \(x) exp(sqrt(x)))
3) or using magrittr
library(magrittr)
lapply(L, . %>% sqrt %>% exp)
4) with purrr. In this case reverse the order of the functions.
library(purrr)
map(L, compose(exp, sqrt))
5) Using Compose from functional is similar to (4) except for the order of functions.
library(functional)
lapply(L, Compose(sqrt, exp))
本文标签: rOptimize using multiple consecutive lapply functionsStack Overflow
版权声明:本文标题:r - Optimize using multiple consecutive lapply functions? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741270112a2369124.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
lapply()
repeatedly, just create an assigned (or anonymous) function of your processing steps and do it in a single call. You may be able to get the data into an appropriate format without needing to transpose a data frame but you'd need to provide a reproducible example for better advice. – lroha Commented Feb 24 at 12:49lapply(lst, \(x) as.data.frame(x) |> t() |> sqrt())
, for instance. – jay.sf Commented Feb 24 at 13:13t()
that's what you are going to get. – Rui Barradas Commented Feb 24 at 13:47mylist
? A list of data frames? Why not binding them to a singlematrix
,data.frame
? – Friede Commented Feb 24 at 14:46