Home > database >  How to create a vector of repeated strings based on a different vector
How to create a vector of repeated strings based on a different vector

Time:12-05

#Hi,

#I'm trying to have a vector of strings with repeated values like this:

[1] "subcarinal, subcarinal"
[2] "subcarinal, subcarinal, subcarinal"

#I want the number of repetitions of each word to be based on a different vector:

x<-  2 0 2 3

#I want the output to be in this case:

[1] "subcarinal, subcarinal"
[2] ""
[3] "subcarinal, subcarinal"
[4] "subcarinal, subcarinal, subcarinal"

#I have tried this and it doesn't work:

dat <- data.frame(name=rep("subcarinal", times=c(x)))

CodePudding user response:

We may use strrep from base R

dat <- data.frame(name = trimws(strrep("subcarinal, ", x), whitespace = ",\\s*"))

-output

> dat
                                name
1             subcarinal, subcarinal
2                                   
3             subcarinal, subcarinal
4 subcarinal, subcarinal, subcarinal

Or using rep

data.frame(name = mapply(function(u, v) toString(rep(u, v)), 
      rep("subcarinal", length(x)), x))

data

x <- c(2, 0, 2, 3)

CodePudding user response:

We can use rep, toString and map:

library(purrr)

string<-'subcarinal'

map_chr(x, ~toString(rep(string, .x)))

[1] "subcarinal, subcarinal"            
[2] ""                                  
[3] "subcarinal, subcarinal"            
[4] "subcarinal, subcarinal, subcarinal"
  • Related