[R] Vectors out of lists?
Bill.Venables at csiro.au
Bill.Venables at csiro.au
Wed Nov 17 01:44:26 CET 2010
Another approach would be
> Y <- list(sqrt, sin, function(u) u/2)
> Ybar <- function(u) rowMeans(sapply(Y, function(fun) fun(u)))
>
> integrate(Ybar, 0, 1)
0.4587882 with absolute error < 5.6e-05
>
i.e. make the function vectorized directly.
Note, however, that if you had
Y[[4]] <- function(u) 1
you would need to be careful and use something like
Y[[4]] <- function(u) rep(1, length(u))
or indeed
Y[[4]] <- Vectorize(function(u) 1)
for the process to work.
Bill Venables.
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Phil Spector
Sent: Wednesday, 17 November 2010 10:24 AM
To: Eduardo de Oliveira Horta
Cc: r-help at r-project.org
Subject: Re: [R] Vectors out of lists?
Eduardo -
Thanks for the reproducible example!
> Y<-list()
> Y[[1]]<-function(u) sqrt(u)
> Y[[2]]<-function(u) sin(u)
> Y[[3]]<-function(u) 1/2*u
> Ybar = function(u)mean(sapply(Y,function(fun)fun(u)))
Since integrate requires a function which accepts a vector
and returns a vector, we'd need to use Vectorize() before
trying to integrate:
> integrate(Vectorize(Ybar),0,1)
0.4587882 with absolute error < 5.6e-05
- Phil Spector
Statistical Computing Facility
Department of Statistics
UC Berkeley
spector at stat.berkeley.edu
On Tue, 16 Nov 2010, Eduardo de Oliveira Horta wrote:
> Thanks, guys... but it seems these suggestions won't work.
>
> Let me try to be more specific with a simple example:
>
> Y<-list()
> Y[[1]]<-function(u) sqrt(u)
> Y[[2]]<-function(u) sin(u)
> Y[[3]]<-function(u) 1/2*u
>
> I wanted something equivalent to
>
> Ybar<-function(u){
> 1/3*(Y[[1]](u) + Y[[2]](u) + Y[[3]](u))
> }
>
> but with arbitrary length(Y) and without using any loops. Also, I can't allow
> for discretization, since I must be able to evaluate Ybar at any u, as I'm
> going to integrate it with the function "integrate".
>
> Thanks again,
>
> Eduardo Horta
>
>
More information about the R-help
mailing list