[R] Compact sums in functions definitions
JeeBee
JeeBee at troefpunt.nl
Thu Jun 15 19:41:12 CEST 2006
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
More information about the R-help
mailing list