Arun
Arun

Reputation: 139

How to concatenate the values in R using loop function?

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?

Upvotes: 1

Views: 11268

Answers (2)

user3710546
user3710546

Reputation:

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."

Upvotes: 6

T.Des
T.Des

Reputation: 90

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) 

Upvotes: 2

Related Questions