xxyyzz xxyyzz - 1 year ago 46
R Question

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 functino to replace all these?

Answer Source

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('|',':','@','*'))
#[1] "this|*[email protected]:" "[email protected]|this*is:"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download