Re: [R] Compact sums in functions definitions

From: JeeBee <JeeBee_at_troefpunt.nl>
Date: Fri 16 Jun 2006 - 03:41:12 EST

Hi Alessandro,

The problem is that arr/x isn't quite doing what you thought it was.
arr / x is something like
c(arr[1] / x[1], arr[2] / x[2], arr[1] / x[3], ...) What I mean is, it divides arr[i] by x[i] and tries to lengthen arr by repeating itself (because it is shorter than x). It warns in case length(x) is not a multiple of length(arr). (or the other way around if arr was longer than x)

I made a nice one for you:
g <- function(x) rowSums( t(t(1/x)) %*% arr )

It is likely someone else can do it much nicer (shorter), my R knowledge still has to be increased ...

JeeBee.

On Thu, 15 Jun 2006 18:55:15 +0200, Alessandro Antonucci wrote:

> I'm trying to make more compact the definition
> of a function as for example:
>
> f <- function(x) 2/x+3/x
>
> by simply defining the array of coefficients
>
> arr = c(2,3)
>
> and setting:
>
> g <- function(x) sum((arr/x))
>
> Everything seems to work fine because the values returned
> by f and g result coincident for different values of their
> argument, but when I try to plot the function g using:
>
> x = seq(-1,1,.01)
> plot(x,g(x))
>
> I receive the errors/warnings:
>

>>Error in xy.coords(x, y, xlabel, ylabel, log) : 
>>        'x' and 'y' lengths differ
>>In addition: Warning message:
>>longer object length
>>        is not a multiple of shorter object length in: b/t 
>>Execution halted

>
> Any idea about that?
>
> Thanks.
>
> Alessandro


R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Jun 16 03:46:19 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Fri 16 Jun 2006 - 06:12:09 EST.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.