Home > Net >  how randomly select from string then concatenate?
how randomly select from string then concatenate?

Time:08-11

how to randomly select 3 words from the vector and then concatenate them separated by single space:

x <-  c("jhonny","devin","Sara","david","Dan")
slt <- sample(x,3,replace = TRUE)
str_to_title(slt)
str_c(slt,sep = " ")

> x <-  c("jhonny","devin","Sara","david","Dan")
> slt <- sample(x,3,replace = TRUE)
> str_to_title(slt)
[1] "David" "Devin" "David"
> str_c(slt,sep = " ")
[1] "david" "devin" "david"

looking for "david devin david"

CodePudding user response:

You could use paste() with collapse = " " to create a single string that has three randomly selected names from x (where x is the data from your question):

slt <- paste(sample(x, 3, replace = TRUE), collapse = " ")

Output:

#[1] "Dan Sara devin"
  •  Tags:  
  • r
  • Related