[R] do calculations as defined by a string / expand mathematical statements in R

R. Michael Weylandt michael.weylandt at gmail.com
Wed Oct 5 22:31:34 CEST 2011


Actually, this may just be a typo in your first post, but if you
actually want to do this calculation:

(array[,,1] + array[,,2] + array[,,3] + array[,,4] + array[,,5] +
array[,,6] + array[,,7] + array[,,8]) / 8

Wouldn't this work?

apply(array,3,sum)/dim(array)[3]


On Wed, Oct 5, 2011 at 4:22 PM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
> Didn't three of us give you a function (in various flavors) that would
> do the mean for variable inputs, reading them from a list? (Though
> David's was admittedly much cooler than mine!)
>
> Anyways, look into parse(text=do) with eval() if you want to go the
> string route.
>
> Michael
>
> On Wed, Oct 5, 2011 at 4:14 PM, Martin Batholdy <batholdy at googlemail.com> wrote:
>> Dear R-group,
>>
>>
>> is there a way to perform calculations that are defined in a string format?
>>
>>
>> for example I have different variables:
>>
>> x1 <- 3
>> x2 <- 1
>> x4 <- 1
>>
>> and a string-variable:
>>
>> do <- 'x1 + x2 + x3'
>>
>>
>> Is there any way to perform what the variable 'do'-describes
>> (just like the formula-element but more elemental)?
>>
>>
>>
>> Perhaps my idea to solve my problem is a little bit strange.
>>
>>
>> My general problem is, that I have to do arithmetics for which there seems to be no function available that I can apply in order to be more flexible.
>>
>>
>> To be precise, I have to add up three dimensional arrays.
>>
>> I can do that like this (as someone suggested on this help-list – thanks for that!):
>>
>> (array[,,1] + array[,,2] + array[,,3]) / 3
>>
>>
>> However in my case it can happen that at some point, I don't have to add 3 but 8 'array-slices'
>> (or 10 or x).
>>
>> And I don't want to manually expand the above statement to:
>>
>> (array[,,1] + array[,,2] + array[,,3] + array[,,4] + array[,,5] + array[,,6] + array[,,7] + array[,,8]) / 8
>>
>> (ok, now I have done it ;)
>>
>>
>>
>> So, my thinking was that I can easily expand and change a string (with the paste-function / repeat-function etc.).
>> But how can I expand a mathematical statement?
>>
>>
>> thanks for any suggestions!
>> ______________________________________________
>> R-help at r-project.org 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.
>>
>



More information about the R-help mailing list