# [R] Alternating between "for loops"

Tue Jul 31 01:28:37 CEST 2012

```Hello,

Maybe something along the lines of

J <- 10
cols <- rep(c(TRUE, TRUE, FALSE, FALSE), 3)[seq_len(J)]
for(i in which(cols)) { do something }
for(i in which(!cols)) { do something else }

Hope this helps,

Em 31-07-2012 00:18, Claudia Penaloza escreveu:
> Dear All,
> I would like to apply two different "for loops" to each set of four columns
> of a matrix (the loops here are simplifications of the actual loops I will
> be running which involve multiple if/else statements).
> I don't know how to "alternate" between the loops depending on which column
> is "running through the loop" at the time.
> ## Set up matrix
> J <- 10
> N <- 10
> y <- matrix(0,N,J)
> ## Apply this loop to the first two of every four columns ([,1:2],
> [,5:6],[,9:10], etc.)
> for (q in 1:N){
> for(j in 1:J){
> if(j %% 2){
> y[q,j]=1
> }else{y[q,j]=2}
> }
> }
> ## Apply this loop to the next two of every four columns
> ([,3:4],[,7:8],[,11:12], etc.)
> for (q in 1:N){
> for(j in 1:J){
> if(j %% 2){
> y[q,j]="A"
> }else{y[q,j]="B"}
> }
> }
> I want to get something like this (preferably without the quotes):
>
>> y
> [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
>   [1,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [2,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [3,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [4,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [5,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [6,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [7,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [8,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>   [9,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
> [10,] "1"  "2"  "A"  "B"  "1"  "2"  "A"  "B"  "1"  "2"
>
>
>
> Any help greatly appreciated!
>
> Claudia
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help