xxyyzz
xxyyzz

Reputation: 63

replace string with a random character from a selection

How can you take the string and replace every instance of ".", ",", " " (i.e. dot, comma or space) with one random character selected from c('|', ':', '@', '*')?

Say I have a string like this

 Aenean ut odio dignissim augue rutrum faucibus. Fusce posuere, tellus eget viverra mattis, erat tellus porta mi, at facilisis sem nibh non urna. Phasellus quis turpis quis mauris suscipit vulputate. Sed interdum lacus non velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

To get one random character, we can treat the characters as a vector then use sample function to select one out. I assume first I need to search for dot, comma or space, then use gsub function to replace all these?

Upvotes: 1

Views: 1212

Answers (2)

akrun
akrun

Reputation: 886948

Here is another option with chartr

pat <- paste(sample(c('|', ';', '@', '*'), 3), collapse="")
chartr('., ', pat, x)
#[1] "this|*is*nice;" "nice|*this*is;"

data

x <- c("this, is nice.", "nice, this is.")

Upvotes: 2

thelatemail
thelatemail

Reputation: 93813

Given your clarification, try this one:

x <- c("this, is nice.", "nice, this is.")
gr <- gregexpr("[., ]", x)
regmatches(x,gr) <- lapply(lengths(gr), sample, x=c('|',':','@','*'))
x
#[1] "this|*is@nice:" "nice@|this*is:"

Upvotes: 3

Related Questions