1

I want an output like this using a loop function:

> stat-1, stat-2, stat-3, stat4, stat5.

Currently this is my code:

x<-0;  
while (x <= 10)  

{  
  x <- x+1  
  z <- paste('stat-', x, collapse = "," ) 
  print(z) 
 }

But iam getting output like this:

[1] "stat- 1"  
[1] "stat- 2"  
[1] "stat- 3"  
[1] "stat- 4"  
[1] "stat- 5"  

How can i get the output in single line?

5
  • 3
    You don't need a loop, paste('stat_', x, collapse=",") where x <- 1:10 Commented Aug 19, 2015 at 9:54
  • Your output is not consistent with what you try to do. You certainly missed some "-". Could you correct for us to be certain of your desired output? Commented Aug 19, 2015 at 9:57
  • 1
    @akrun collapse=", " will insert a space after the comma. Commented Aug 19, 2015 at 9:58
  • 2
    to remove the space between the - and the number, use: paste0('stat-', x, collapse = "," ) Commented Aug 19, 2015 at 9:59
  • The answer you choose doesn't match your request. Commented Aug 20, 2015 at 3:52

2 Answers 2

6

You don't need a for loop:

x <- 1:5

paste0("stat-", x, collapse = ", ")
# [1] "stat-1, stat-2, stat-3, stat-4, stat-5"

If you want a terminal ".":

paste0(paste0("stat-", x, collapse = ", "), ".")
# [1] "stat-1, stat-2, stat-3, stat-4, stat-5."
Sign up to request clarification or add additional context in comments.

Comments

2

If you want several string you can also try :

x<-0;
z<-NULL; 
while (x <= 10)  {  
 x <- x+1  
 z <- c(z,paste('stat-', x, collapse = "," ))
}
print(z) 

1 Comment

The OP would like a single line as output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.