Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2 variables in a for loop in R

Tags:

for-loop

r

I have two vectors that I would like to reference in a for loop, but each is of different lengths.

n=1:50
m=letters[1:14]

I tried a single loop to read it

for (i in c(11:22,24,25)){
    cat (paste(n[i],m[i],sep='\t'),sep='\n')
}

and ended up with:

11  k
12  l
13  m
14  n
15  NA
16  NA
17  NA
18  NA
19  NA
20  NA
21  NA
22  NA
24  NA
25  NA

but I would like to obtain:

11  a
12  b
13  c
...
25  n

is there a way to have a double variable declaration?

for (i in c(11:22,24,25) and j in 1:14){
    cat (paste(n[i],m[j],sep='\t'),sep='\n')
}

or something similar to get the result I want?

like image 638
frank Avatar asked Dec 22 '25 02:12

frank


1 Answers

No there isn't. But you can do this:

ind_j <- c(11:22,24,25)
ind_k <- 1:14
for (i in seq_along(ind_j)){
  cat (paste(n[ind_j[i]],m[ind_k[i]],sep='\t'),sep='\n')
}

Of course, it's very probable that you shouldn't use a for loop for your actual problem.

like image 53
Roland Avatar answered Dec 23 '25 14:12

Roland