Re: [R] Applying a function to each element of an array

From: Kjetil Holuerson <kjetil_at_redcotel.bo>
Date: Sat 08 Oct 2005 - 05:24:47 EST

Tim Smith wrote:
> Hi,
>
> I have a 7000x7000 matrix, and each element is an integer. For each element, I want to apply the function :
>
> wt <- 0
> for(q in 1:count){
> wt <- wt + 0.5^(q-1)
> }
>

This is not a function! Maybe you want

helper <- function(count) sum(0.5^((1:count)-1))

> I get the value of 'count' from the elements in the matrix , and want to store the corresponding 'wt' value for that element.
>
> I suppose I could loop through the matrix, and apply the function to each element but this would take a really really long time. Are there any quicker ways to get the same result?
>
> many thanks,

mapply(helper, yourmat)

gives you the elements of the matrix, as a vector. So you only must reassemble as a matrix:

n <- nrow(yourmat)
p <- ncol(yourmat)
matrix( mapply(helper, yourmat), n, p)

Kjetil

>
> Tim
>
>
> ---------------------------------
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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
>
>

--

______________________________________________
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 Sat Oct 08 12:44:25 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 18:31:28 EST