Berbery
Berbery

Reputation: 297

Use a counter in for loop to take a counting result

I would like to have as output this:

This is the text [1] from process
This is the text [2] from process
This is the text [3] from process

How can I make it using a for loop? What I tried:

for (i in 1:3) {
                  query_line<- "This is the text["+i+"]from process"
  }

And the error is:

Error in "This is the text[" + i : non-numeric argument to binary operator

Upvotes: 0

Views: 46

Answers (2)

talat
talat

Reputation: 70246

You can use ?cat:

for (i in 1:3) {
    cat("This is the text [", i, "] from process\n")
}
#This is the text [ 1 ] from process
#This is the text [ 2 ] from process
#This is the text [ 3 ] from process

If you just want to store it in a variable, you can do the following (don't forget to initialize the storage variable in advance):

n <- 3
res <- character(n)
for (i in 1:n) {
   res[i] <- paste("This is the text [", i, "] from process")
}

Then, results are stored in res:

res
#[1] "This is the text [ 1 ] from process" "This is the text [ 2 ] from process"
#[3] "This is the text [ 3 ] from process"

However, if you really just wanted to create a character vector with that text, you could do it in a single paste call:

paste("This is the text [", 1:3, "] from process")
#[1] "This is the text [ 1 ] from process" "This is the text [ 2 ] from process"
#[3] "This is the text [ 3 ] from process"

Upvotes: 1

CuriousBeing
CuriousBeing

Reputation: 1632

You can also use the message function which generates diagnostic message. It is displayed in red.

 for (i in 1:5)
 message(paste("This is the text [",i,"] from process",sep=""))

Upvotes: 1

Related Questions