Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R loop over two or more vectors simultaneously - paralell

Tags:

loops

iteration

r

I was looking for method to iterate over two or more character vectors/list in R simultaneously ex. is it some way to do something like:

foo <- c('a','c','d')
bar <- c('aa','cc','dd')

for(i in o){
  print(o[i], p[i])
}

Desired result:

'a', 'aa'
'c', 'cc'
'd', 'dd'

In Python we can do simply:

foo = ('a', 'c', 'd')
bar = ('aa', 'cc', 'dd')

for i, j in zip(foo, bar):
    print(i, j)

But can we do this in R?

like image 348
Adamm Avatar asked Oct 24 '17 11:10

Adamm


4 Answers

Like this?

foo <- c('a','c','d')
bar <- c('aa','cc','dd')

for (i in 1:length(foo)){
  print(c(foo[i],bar[i]))
}

[1] "a"  "aa"
[1] "c"  "cc"
[1] "d"  "dd"

Works under the condition that the vectors are the same length.

like image 71
brettljausn Avatar answered Nov 08 '22 09:11

brettljausn


In R, you rather iterate based on the indices than on vectors directly:

for (i in 1:(min(length(foo), length(bar)))){
     print(foo[i], bar[i])
}
like image 41
Pop Avatar answered Nov 08 '22 09:11

Pop


Another option is to use mapply. This wouldn't make a lot of sense for printing, but I'm assuming you have an interest in doing this for something more interesting than print

foo <- c('a','c','d')
bar <- c('aa','cc','dd')

invisible(
  mapply(function(f, b){ print(c(f, b))},
         foo, bar)
)
like image 43
Benjamin Avatar answered Nov 08 '22 10:11

Benjamin


Maybe someone arriving based on the title makes good use of this:

foo<-LETTERS[1:10]
bar<-LETTERS[1:3]
i = 0
for (j in 1:length(foo)){
  i = i + 1
  if (i > length(bar)){
    i = 1
  }
  print(paste(foo[j],bar[i]) )
}

[1] "A A"
[1] "B B"
[1] "C C"
[1] "D A"
[1] "E B"
[1] "F C"
[1] "G A"
[1] "H B"
[1] "I C"
[1] "J A"

which is "equivalent" to: (using for eases assignments)

suppressWarnings(invisible(
  mapply(function(x, y){ 
         print(paste(x, y))},
         foo, bar)
))
like image 1
Ferroao Avatar answered Nov 08 '22 10:11

Ferroao