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:
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.
Your
print
is broken, attempting to passdigits=n2
(andquote=n
), which obviously won't work. I suspect you needsprintf
.
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.