[R] summing elements in a list of functions

classic Classic list List threaded Threaded
15 messages Options
Reply | Threaded
Open this post in threaded view
|

[R] summing elements in a list of functions

James Foadi
Dear all,
I have looked for an answer for a couple of days, but can't come with any
solution.

I have a set of functions, say:

> t0 <- function(x) {1}
> t1 <- function(x) {x}
> t2 <- function(x) {x^2}
> t3 <- function(x) {x^3}

I would like to find a way to add up the previous 4 functions and obtain a new
function:

> rrr <- function(x) {1+x+x^2+x^3}

without, actually, having to write it in the previous form (I could have cases
with hundreds of functions). I thought that perhaps I could first define a
list of functions:

> ttt <- list(t0,t1,t2,t3)

and then I could use something like "sum", to add up all the elements of the
list and obtain another function. I've tried:

> rrr <- function(x) {sum(ttt)}

but it does not work.

Any help with this is greatly appreciated.

Cheers,

james
--
Dr James Foadi
Department of Physics
University of York
York YO10 5DD

email: [hidden email]
web page: http://www-users.york.ac.uk/~jf117
Tel: 0044 1904 434622
Mobile: 0044 7740 678548

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] summing elements in a list of functions

Gabor Grothendieck
Try this:


L <- list(function(x) 1, function(x) x, sin, cos)
sumL <- function(x) sum(sapply(L, function(f) f(x)))
sumL(pi) # pi


On 10/20/06, James Foadi <[hidden email]> wrote:

> Dear all,
> I have looked for an answer for a couple of days, but can't come with any
> solution.
>
> I have a set of functions, say:
>
> > t0 <- function(x) {1}
> > t1 <- function(x) {x}
> > t2 <- function(x) {x^2}
> > t3 <- function(x) {x^3}
>
> I would like to find a way to add up the previous 4 functions and obtain a new
> function:
>
> > rrr <- function(x) {1+x+x^2+x^3}
>
> without, actually, having to write it in the previous form (I could have cases
> with hundreds of functions). I thought that perhaps I could first define a
> list of functions:
>
> > ttt <- list(t0,t1,t2,t3)
>
> and then I could use something like "sum", to add up all the elements of the
> list and obtain another function. I've tried:
>
> > rrr <- function(x) {sum(ttt)}
>
> but it does not work.
>
> Any help with this is greatly appreciated.
>
> Cheers,
>
> james
> --
> Dr James Foadi
> Department of Physics
> University of York
> York YO10 5DD
>
> email: [hidden email]
> web page: http://www-users.york.ac.uk/~jf117
> Tel: 0044 1904 434622
> Mobile: 0044 7740 678548
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] summing elements in a list of functions

Peter Dalgaard
In reply to this post by James Foadi
James Foadi <[hidden email]> writes:

> Dear all,
> I have looked for an answer for a couple of days, but can't come with any
> solution.
>
> I have a set of functions, say:
>
> > t0 <- function(x) {1}
> > t1 <- function(x) {x}
> > t2 <- function(x) {x^2}
> > t3 <- function(x) {x^3}
>
> I would like to find a way to add up the previous 4 functions and obtain a new
> function:
>
> > rrr <- function(x) {1+x+x^2+x^3}
>
> without, actually, having to write it in the previous form (I could have cases
> with hundreds of functions). I thought that perhaps I could first define a
> list of functions:
>
> > ttt <- list(t0,t1,t2,t3)
>
> and then I could use something like "sum", to add up all the elements of the
> list and obtain another function. I've tried:
>
> > rrr <- function(x) {sum(ttt)}
>
> but it does not work.
>
> Any help with this is greatly appreciated.

rrr <- function(x) sum(sapply(ttt,function(f)f(x)))

--
   O__  ---- Peter Dalgaard             Ă˜ster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - ([hidden email])                  FAX: (+45) 35327907

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] summing elements in a list of functions

jholtman
In reply to this post by James Foadi
will this work for you?

> t0 <- function(x) {1}
> t1 <- function(x) {x}
> t2 <- function(x) {x^2}
> t3 <- function(x) {x^3}
>
> t.l <- list(t0,t1,t2,t3)
> t.l
[[1]]
function(x) {1}

[[2]]
function(x) {x}

[[3]]
function(x) {x^2}

[[4]]
function(x) {x^3}


> arg.val <- 4  # evaluate for 4

> sum(unlist(lapply(t.l, function(x)x(arg.val))))
[1] 85




On 10/20/06, James Foadi <[hidden email]> wrote:

> Dear all,
> I have looked for an answer for a couple of days, but can't come with any
> solution.
>
> I have a set of functions, say:
>
> > t0 <- function(x) {1}
> > t1 <- function(x) {x}
> > t2 <- function(x) {x^2}
> > t3 <- function(x) {x^3}
>
> I would like to find a way to add up the previous 4 functions and obtain a new
> function:
>
> > rrr <- function(x) {1+x+x^2+x^3}
>
> without, actually, having to write it in the previous form (I could have cases
> with hundreds of functions). I thought that perhaps I could first define a
> list of functions:
>
> > ttt <- list(t0,t1,t2,t3)
>
> and then I could use something like "sum", to add up all the elements of the
> list and obtain another function. I've tried:
>
> > rrr <- function(x) {sum(ttt)}
>
> but it does not work.
>
> Any help with this is greatly appreciated.
>
> Cheers,
>
> james
> --
> Dr James Foadi
> Department of Physics
> University of York
> York YO10 5DD
>
> email: [hidden email]
> web page: http://www-users.york.ac.uk/~jf117
> Tel: 0044 1904 434622
> Mobile: 0044 7740 678548
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] summing elements in a list of functions

Giovanni Petris
In reply to this post by James Foadi

Here is one way. To have a vectorized version you need to redefine
't0', though

t0 <- function(x) {1}
t1 <- function(x) {x}
t2 <- function(x) {x^2}
t3 <- function(x) {x^3}
ttt <- list(t0,t1,t2,t3)

rrr <- function(x) sum(sapply(seq(along=ttt), function(i) ttt[[i]](x)))

## vectorized version
ttt[[1]] <- t0 <- function(x) rep(1, length(x))
rrr2 <- function(x) rowSums(sapply(seq(along=ttt), function(i) ttt[[i]](x)))

Hope this helps,
Giovanni

> Date: Fri, 20 Oct 2006 15:19:06 +0100
> From: James Foadi <[hidden email]>
> Sender: [hidden email]
> Precedence: list
> User-Agent: KMail/1.9.4
>
> Dear all,
> I have looked for an answer for a couple of days, but can't come with any
> solution.
>
> I have a set of functions, say:
>
> > t0 <- function(x) {1}
> > t1 <- function(x) {x}
> > t2 <- function(x) {x^2}
> > t3 <- function(x) {x^3}
>
> I would like to find a way to add up the previous 4 functions and obtain a new
> function:
>
> > rrr <- function(x) {1+x+x^2+x^3}
>
> without, actually, having to write it in the previous form (I could have cases
> with hundreds of functions). I thought that perhaps I could first define a
> list of functions:
>
> > ttt <- list(t0,t1,t2,t3)
>
> and then I could use something like "sum", to add up all the elements of the
> list and obtain another function. I've tried:
>
> > rrr <- function(x) {sum(ttt)}
>
> but it does not work.
>
> Any help with this is greatly appreciated.
>
> Cheers,
>
> james
> --
> Dr James Foadi
> Department of Physics
> University of York
> York YO10 5DD
>
> email: [hidden email]
> web page: http://www-users.york.ac.uk/~jf117
> Tel: 0044 1904 434622
> Mobile: 0044 7740 678548
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>


--

 __________________________________________________
[                                                  ]
[ Giovanni Petris                 [hidden email] ]
[ Department of Mathematical Sciences              ]
[ University of Arkansas - Fayetteville, AR 72701  ]
[ Ph: (479) 575-6324, 575-8630 (fax)               ]
[ http://definetti.uark.edu/~gpetris/              ]
[__________________________________________________]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] summing elements in a list of functions

James Foadi
In reply to this post by Gabor Grothendieck
Many thanks to those who have answered my question.
Could I ask Gabor and Peter the meaning of:

> sum(sapply(ttt,function(f) f(x)))

I gather that a "mysterious" function f(x) is applied to all components of
ttt, and sum can act on this modified object. But what is exactly f? And how
does the list object change?

Cheers,

J

--
Dr James Foadi
Department of Physics
University of York
York YO10 5DD

email: [hidden email]
web page: http://www-users.york.ac.uk/~jf117
Tel: 0044 1904 434622
Mobile: 0044 7740 678548

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] summing elements in a list of functions

Gabor Grothendieck
ttt is a list of functions so each function in ttt is passed in turn to
the anonymous function as argument f.

On 10/20/06, James Foadi <[hidden email]> wrote:

> Many thanks to those who have answered my question.
> Could I ask Gabor and Peter the meaning of:
>
> > sum(sapply(ttt,function(f) f(x)))
>
> I gather that a "mysterious" function f(x) is applied to all components of
> ttt, and sum can act on this modified object. But what is exactly f? And how
> does the list object change?
>
> Cheers,
>
> J
>
> --
> Dr James Foadi
> Department of Physics
> University of York
> York YO10 5DD
>
> email: [hidden email]
> web page: http://www-users.york.ac.uk/~jf117
> Tel: 0044 1904 434622
> Mobile: 0044 7740 678548
>

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

[R] I really don't understand functions in R :-)

ALBERTO VIEIRA FERREIRA MONTEIRO
An example:

n <- 3
f <- function(x) x^n
f(2)
# [1] 8
n <- 2
f(2)
# [1] 4
f
# function(x) x^n

Ok, I know this is trivial, because function f is foverer bound
to the variable n. But how can I _fix_ n when I define _f_, so
that changing _n_ won't change the function f?

Alberto Monteiro

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] I really don't understand functions in R :-)

jholtman
It sounds like you want to use 'local' to create private variables:


> # your example
> n <- 3
> f <- function(x) x^n
> f(2)
[1] 8
> n<-1
> f(2)
[1] 2
> # now using 'local' to make 'n' private
> f <- local({
+ n <- 3
+ function(x) x^n
+ })
> f(2)
[1] 8
> n <- 1
> f(2)
[1] 8
>

Or why not just pass 'n' to the function

On 10/20/06, Alberto Monteiro <[hidden email]> wrote:

> An example:
>
> n <- 3
> f <- function(x) x^n
> f(2)
> # [1] 8
> n <- 2
> f(2)
> # [1] 4
> f
> # function(x) x^n
>
> Ok, I know this is trivial, because function f is foverer bound
> to the variable n. But how can I _fix_ n when I define _f_, so
> that changing _n_ won't change the function f?
>
> Alberto Monteiro
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] I really don't understand functions in R :-)

Thomas Lumley
In reply to this post by ALBERTO VIEIRA FERREIRA MONTEIRO
On Fri, 20 Oct 2006, Alberto Monteiro wrote:

> An example:
>
> n <- 3
> f <- function(x) x^n
> f(2)
> # [1] 8
> n <- 2
> f(2)
> # [1] 4
> f
> # function(x) x^n
>
> Ok, I know this is trivial, because function f is foverer bound
> to the variable n. But how can I _fix_ n when I define _f_, so
> that changing _n_ won't change the function f?

You need to make sure that n is stored inside the function. One approach
is to write a function that makes functions like f():

> make.f<-function(n) {function(x) x^n}
> n<-2
> f2<-make.f(n)
> n<-3
> f3<-make.f(n)
> f2(2)
[1] 4
> f3(2)
[1] 8

f2() and f3() each have a private copy of n from their enclosing
environment.

  -thomas

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] I really don't understand functions in R :-)

Kevin E. Thorpe
In reply to this post by ALBERTO VIEIRA FERREIRA MONTEIRO
Is this what you want?

> f <- function(x,n=3) x^n
> f(2)
[1] 8
> n <- 2
> f(2)
[1] 8
> f(2,2)
[1] 4


Alberto Monteiro wrote:

> An example:
>
> n <- 3
> f <- function(x) x^n
> f(2)
> # [1] 8
> n <- 2
> f(2)
> # [1] 4
> f
> # function(x) x^n
>
> Ok, I know this is trivial, because function f is foverer bound
> to the variable n. But how can I _fix_ n when I define _f_, so
> that changing _n_ won't change the function f?
>
> Alberto Monteiro


--
Kevin E. Thorpe
Biostatistician/Trialist, Knowledge Translation Program
Assistant Professor, Department of Public Health Sciences
Faculty of Medicine, University of Toronto
email: [hidden email]  Tel: 416.946.8081  Fax: 416.946.3297

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] I really don't understand functions in R :-)

ALBERTO VIEIRA FERREIRA MONTEIRO
In reply to this post by jholtman
Jim Holtman wrote:
>
> It sounds like you want to use 'local' to create private variables:
>
Ok, so, in a "real world" example, I should do something
like this:

n <- 3 # but here there is some very complex computations
# that give me a value for n
f <- local({
  f.n <- n
  function(x) x^f.n
})
f(2)
# 8
n <- 2
f(2)
# 8

Thanks for the enlightnment :-)

Alberto Monteiro

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] I really don't understand functions in R :-)

Giovanni Petris
In reply to this post by ALBERTO VIEIRA FERREIRA MONTEIRO

May I am missing something, but it seems to me that the easiest way to
solve your problem, if you don't want to change 'n', is to define

f <- function(x) x^3

If you want to allow the possibility for 'n' to change, you can
include it as an argument of 'f'

f <- function(x,n=3) x^n

Best,
Giovanni

> Date: Fri, 20 Oct 2006 14:41:26 -0200
> From: Alberto Monteiro <[hidden email]>
> Sender: [hidden email]
> Precedence: list
>
> An example:
>
> n <- 3
> f <- function(x) x^n
> f(2)
> # [1] 8
> n <- 2
> f(2)
> # [1] 4
> f
> # function(x) x^n
>
> Ok, I know this is trivial, because function f is foverer bound
> to the variable n. But how can I _fix_ n when I define _f_, so
> that changing _n_ won't change the function f?
>
> Alberto Monteiro
>
> ______________________________________________
> [hidden email] mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
>

--

 __________________________________________________
[                                                  ]
[ Giovanni Petris                 [hidden email] ]
[ Department of Mathematical Sciences              ]
[ University of Arkansas - Fayetteville, AR 72701  ]
[ Ph: (479) 575-6324, 575-8630 (fax)               ]
[ http://definetti.uark.edu/~gpetris/              ]
[__________________________________________________]

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] I really don't understand functions in R :-)

Marcin Jaworski
In reply to this post by ALBERTO VIEIRA FERREIRA MONTEIRO
jim holtman ([hidden email]) wrote:

>It sounds like you want to use 'local' to create private variables:

Hello,

I hope I do not disturb your discussion very much writing in this
thread but the topic sounded extremely familiar for me :)

My only question is:

Is there a good book or more general - any resources that can be
used as a reader-friendly introduction to programming (statistical)
functions in R, regarding the fact that potential reader have no
programming background at all ("at all" means that such constructs
like 'for', 'while' and practical usage of them are mistery)?

-----------------------------------------------------------------
Below is a rationale for the above question, probably unnecessary
thus skippable.
-----------------------------------------------------------------

Unfortunately, I have no experience in programming at all, but
I found R very usefull for statistical analysis and graphics.
There's a lot of great literature focused on how to apply
statistical models in R. It would be great to customize the power
of R for individual needs. It appeared to me very quickly that
such task requires using constructs like "for" or "while".
I am ready to learn programming to use R efficiently.

My problem is that I can prepare an expression that executes a
sequence of specific commands, but I cannot figure it out how
to make the commands conditional or looping to get what I really
need.

For instance, the example below calculates Cronbach's alpha
(actually, I found more elegant way in the www, and even package
psych that includes a function bringing identical results):


alfa<-function(df) {
not_empty_df<-df[ !is.na( df[ ,no_of_col<-length(vector<-c(1:(ncol
(df))))] )==TRUE , ]
no_of_variables<-ncol(not_empty_df)
no_of_cases<-nrow(not_empty_df)
var_covar<-var(not_empty_df,na.rm=T)
alfa<-(no_of_variables/(no_of_variables-1)*(1-sum(diag(var_covar))/sum
(var_covar)))
Alfa<-alfa
cat("Cronbach's alpha: ");print(Alfa,digits=3);
cat("Number of items in hand: ");print(no_of_variables)
cat("Number of cases: ");print(no_of_cases)
}

I can imagine that one can write function that shows values
of Cronbach's alpha when subsequent variables in data frame
are deleted separately, that is they are back in data frame
again when there is the time for neighbour of previously
deleted variable to be ommited during calculation. To be true,
I do not want to know how the function should look like exectly.
It would be pleasure for me to write such function by myself.
I guess grouping, loops and/or conditional execution (as
described in "An Introduction to R") is necessary to build
such function.

It's a shame of me but I cannot understand the idea of "for",
"while" and "repeat" after reading few pages of Introduction.
I need more readable recources for dummies. Could you help me,
pleaase?

Best regards,
Marcin Jaworski

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Reply | Threaded
Open this post in threaded view
|

Re: [R] I really don't understand functions in R :-)

Marcin Jaworski
Patrick Burns ([hidden email]) wrote:

>You may be interested in S Poetry.

Hi,
I do find your book very helpful. Thank you.

Best regards,
Marcin Jaworski

______________________________________________
[hidden email] mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.