Jim Maas
2014-Mar-14 13:32 UTC
[R] apply a function containing a reduce statement to all rows of a 2d array?
If possible I would like to apply a function, that contains a "reduce"
statement, across the rows of 2d array. This code works for me right up
until the last. Can it be done or is there a better way? My next challenge
is to pass it a vector of starting values, i.e. each row will have a
different initial value.
func1 <- function (x,y) {x * 0.6}
Reduce(func1, x = seq_len(10), accumulate = TRUE, init = 3)
totalfunc <- function (x) {Reduce(func1, x = seq_len(10),
accumulate = TRUE, init = 3)
}
totalfunc(0)
startarray <- t(array(1:100, c(10,10)))
newarray <- apply(x = startarray, margin = 1, fun = totalfunc)
Thanks
J
--
Jim Maas
[[alternative HTML version deleted]]
Bert Gunter
2014-Mar-14 15:29 UTC
[R] apply a function containing a reduce statement to all rows of a 2d array?
Ummm...
totalfunc(0)
totalfunc(100)
totalfunc() always gives the same result, because its argument is not
used in the function body. You probably want something like:
totalfunc <- function (y,z) {Reduce(func1, x = y,
accumulate = TRUE, init = z)
}
Also note that your argument names in your apply call are all wrong (I
leave it to you to figure out why). Which all suggests that you really
needed to (re?)-read An Introduction to R or other web tutorial (there
are many good ones).
-- Bert
Bert Gunter
Genentech Nonclinical Biostatistics
(650) 467-7374
"Data is not information. Information is not knowledge. And knowledge
is certainly not wisdom."
H. Gilbert Welch
On Fri, Mar 14, 2014 at 6:32 AM, Jim Maas <jimmaasuk at gmail.com>
wrote:> If possible I would like to apply a function, that contains a
"reduce"
> statement, across the rows of 2d array. This code works for me right up
> until the last. Can it be done or is there a better way? My next challenge
> is to pass it a vector of starting values, i.e. each row will have a
> different initial value.
>
> func1 <- function (x,y) {x * 0.6}
> Reduce(func1, x = seq_len(10), accumulate = TRUE, init = 3)
>
> totalfunc <- function (x) {Reduce(func1, x = seq_len(10),
> accumulate = TRUE, init = 3)
> }
>
> totalfunc(0)
>
> startarray <- t(array(1:100, c(10,10)))
>
> newarray <- apply(x = startarray, margin = 1, fun = totalfunc)
>
>
> Thanks
>
> J
>
> --
> Jim Maas
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.