Home > database >  Iterating multiple variables within For Loop in R
Iterating multiple variables within For Loop in R

Time:10-31

How would I be able to create a for loop where it will take in 2 parameters num and names and iterates them both in the for loop. How would I be able to do that?

num<-c(1,2,3)
names<-c('one','two','three')
for (n in num, n2 in names) {
    print("%s : %i",n2,n)
}

CodePudding user response:

  1. You can't iterate over two vectors like that, you need to index over one vector that indexes among them both, and then subset your vectors manually.

  2. Your print is broken, attempting to pass digits=n2 (and quote=n), which obviously won't work. I suspect you need sprintf.

num<-c(1,2,3)
names<-c('one','two','three')
for (i in seq_along(num)) {
    n <- num[i]
    n2 <- names[i]
    print(sprintf("%s : %i",n2,n))
}
# [1] "one : 1"
# [1] "two : 2"
# [1] "three : 3"

BTW: this presumes that all such vectors are the same length.

  • Related