# [R] RE : for loops

Petr Klasterecky klaster at karlin.mff.cuni.cz
Wed Apr 25 13:59:11 CEST 2007

```I know that a looping solution was requested, but this is exactly what
apply() should be used for...

Petr

justin bem napsal(a):
> You can see with this simple example.
>
> matrix.t.test<-function(mx){
>
> p<-dim(mx)[2]  #number of column in the matrix
> n<-dim(mx)[1]  #number of row
>
> n.tests<- p*(p-1)/2 #Number of tests to be done
>
> tested.var <-rep("",n.tests) #Keep rang of tested
> column
> r.t.stat<-rep(0, n.tests)#contain t.stat
> r.p.val <-rep(0, n.tests)#contain p.values
>
> ctst<-1 #current test
> for (i in 1:(p-1)){
>   for (j in (i+1):p){
>     r.t.stat[ctst]<-t.test(mx[,i],mx[,j])\$statistic
>     r.p.val [ctst] <-t.test(mx[,i],mx[,j])\$p.value
>     tested.var [ctst]<-paste(i,"-",j)
>     ctst<-ctst+1
>   }
> }
>
> result<-data.frame(tested.var,r.t.stat,r.p.val)
> return(result)
> }
>
> matrix.t.test(matrix(rnorm(50),nr=10,nc=5))
>
>
>
>
>
>
>
>
>
> --- "silvia-montagna at libero.it"
> <silvia-montagna at libero.it> a écrit :
>
>> Hello everybody
>> I'm very new at using R so probably this is a very
>> stupid question.
>> I have a matrix of "p" columns and I have to
>> calculate for each of them the "two sample
>> t-statistic" and p-value and to save the results
>> into two different vectors.
>> I have divided my matrix into two submatrices:
>> submatrix A containing the first "n1" rows (p
>> columns) and submatrix B containing the remaining
>> "n2" (total rows=n1+n2).
>> How can I do this with for loop construction?
>> Friendly regards
>> Silvia
>>
>>
>>
> ------------------------------------------------------
>> senza canone Telecom
>>
>> ______________________________________________
>> R-help at stat.math.ethz.ch mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained,
>> reproducible code.
>>
>
>
> Justin BEM
> Elève Ingénieur Statisticien Economiste
> BP 294 Yaoundé.
> Tél (00237)9597295.
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.
>
>

--
Petr Klasterecky
Dept. of Probability and Statistics
Charles University in Prague
Czech Republic

```