Home > database >  How to use `paste0` with a vector name to the end in R in for loop
How to use `paste0` with a vector name to the end in R in for loop

Time:10-22

I'm working on a paste0 code using for loop and a vector's name. I want to make a vector become like

[chr] 1 2 3 4 5

But paste0 is usually used with each of vector's values like this

paste0("1", "2", "3", "4", "5")

So I'm confused how I can make this with vector's only name ds. Below is what I tried but returned only 1

ds <- c("1","2","3","4","5")

 for (i in 1:length(ds)) {
    ans <- paste0(ds[i])
  }
  
 ans

CodePudding user response:

You might be looking for:

paste('[chr] ', paste(ds, collapse=' '), sep='')
# [1] "[chr] 1 2 3 4 5"

or:

cat('[chr]', paste(ds, collapse=' '))
# [chr] 1 2 3 4 5

Using a for loop we can do

ans <- '[chr]'
for (i in ds) ans <- paste(ans, i)
ans
# [1] "[chr] 1 2 3 4 5"

CodePudding user response:

Loop: As you asked for a specific loop answer. You can simplify the loop:

ds <- c("1", "2", "3", "4", "5")
ans <- NULL #Delete existing answer if exists
for (i in ds) {
  ans <- paste(c(ans, i), collapse=" ")
}
ans
# [1] "1 2 3 4 5"

Base no loop:

paste0(ds, collapse = " ")
# [1] "1 2 3 4 5"
gsub(",","",toString(ds))

Tidyverse Stringr:

stringr::str_flatten(ds, " ")
stringr::str_c(ds, collapse=" ")
  • Related