Project Brots
Project Brots

Reputation: 43

Transform "for" in "foreach" in R

How may I change the simple "for" to "foreach" in R Language, with sample:

X  <- c("A", "B", "C", "D")

for (i in X)  { 

  if (i == "A") { 
    print("Vogal") 
  }
}  

And in foreach, how can I do?

Upvotes: 1

Views: 263

Answers (1)

nrussell
nrussell

Reputation: 18612

You can iterate over X like this:

library(foreach)
library(iterators)
##
X  <- c("A", "B", "C", "D")
##
foreach(i=iter(X),.combine=c) %do% { 
  if(i=="A") "Vogal" 
}
[1] "Vogal"

Edit: Apparently this works without making an iterator out of X - thank you @flodel:

foreach(i=X,.combine=c) %do% { 
  if(i=="A") "Vogal" 
}
##
[1] "Vogal"

Upvotes: 2

Related Questions