non-numeric_argument
non-numeric_argument

Reputation: 658

How to address the position number of a vector in a loop using R?

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

Answers (2)

rrs
rrs

Reputation: 9913

what about looping over 1:length(strvec)?

Upvotes: 1

Roland
Roland

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

Related Questions