Reputation: 658
Possibly, this is terrible easy, but I am at a loss right now. I want to address the position number of vector which I am looping over. Here is a very reduced example, of course the function(s) I would like to loop over is much more complex than print
. Instead of "test_abc", I would like to get "test_1" and so forth.
strvec <- c("abc", "def", "ghi")
for (i in strvec) {
print(paste("test_", i, sep=""))
print(paste("test_", i[i], sep=""))
}
Upvotes: 0
Views: 46
Reputation: 132706
strvec <- c("abc", "def", "ghi")
for (i in seq_along(strvec)) {
print(paste("test_", i, sep=""))
print(paste("test_", strvec[i], sep=""))
}
#[1] "test_1"
#[1] "test_abc"
#[1] "test_2"
#[1] "test_def"
#[1] "test_3"
#[1] "test_ghi"
However, there is a very good chance that there are much better (and probably faster) alternatives to a for
loop to reach your final goal.
Upvotes: 2