[R] the function doesn´t work

Joshua Wiley jwiley.psych at gmail.com
Mon Sep 27 00:35:13 CEST 2010


On Sun, Sep 26, 2010 at 3:16 PM, jethi <kartija at hotmail.com> wrote:
>
> thnx again. now i understand my big problem. ok so now a want to watch the
> probabilities p, which are do this for example
> p[1,1]=cor(x1,y1)/(cor(x1,y1)+..+cor(xm,ym)).
>
>
> so
> N = 10
> n = 100
> m = 2
> k = n/m
> l = matrix(0,nrow=m,ncol=N)
> p=matrix(0,nrow=m,ncol=N)
>
> for(i in 1:N){
>  x=rnorm(n,0,0.5)
>  y=rnorm(n,0,0.8)
>  for(j in 1:m){
>    l[j,i] = cor(
>       (x[(((j-1)*k)+1):(((j-1)*k)+k)]),
>       (y[(((j-1)*k)+1):(((j-1)*k)+k)]))
>
>
>  }
> }
> for(i in 1:N){
> for (j in 1:m){
> p[j,i]=l[j,i]^2/sum(l[,i]^2)
> }
> }
>
>
>
> i didn´t write the matrix in the first loop with "l", because if i do that,
> he takes at first only the first value. and then the first and the second
> value of l. so its wrong.

This is true, it sounds like you're starting to get a better feel for
what is happening.  Just as another option, you can use the apply()
function to apply something to each column of a matrix, for instance:

## it uses the function apply() to apply to each column of l
## my simple function(z) which squares each element of z and divides
## by the sum of squares
p2 <- apply(l, 2, function(z) {(z^2)/sum(z^2)})
## verify that the for loop and apply method produce identical results
identical(p, p2)

You would still have to do this after you had completely calculated
all of the correlations.

> because of it i take a new two loops which make
> exactly what i want.

So is everything working for you now?

>
> regards
> jethi
>
> --
> View this message in context: http://r.789695.n4.nabble.com/the-function-doesn-t-work-tp2714105p2714755.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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