Home > database >  Concatenate each word in a vector to form a single string in r
Concatenate each word in a vector to form a single string in r

Time:04-02

I am trying to combine the values of a vector to a single string separated with | in between each concatenation.

For example:

library(tidyverse)

sample_df <- data.frame("sample_col" = c("Audi","BMW","MG","Hyundai","Kia"),
                        "value" = c(22,44,66,88,19))  

Tried:

paste(sample_df$sample_col, "|")

output

[1] "Audi |"     "BMW |"       "MG |"        "Hyundai |"   "Kia|"

Need Result like:

Audi |BMW |MG |Hyundai |Kia|

I am trying to do this as I will be searching each word mentioned above and str_detect(col_name, pattern = sample_df$sample_col) doesn't work correctly and to be able to search each word I need them in

str_detect(col_name,pattern = "word1|word2|word3")

format.

CodePudding user response:

Try:

library(tidyverse)

str_c(sample_df$sample_col, collapse = "|")

#> [1] "Audi|BMW|MG|Hyundai|Kia"
  • Related