用选择中的随机字符替换字符串

时间:2017-05-23 03:01:26

标签: r string random replace

如何获取字符串并将"."","" "(即点,逗号或空格)的每个实例替换为从c('|', ':', '@', '*')中选择的一个随机字符?

说我有这样的字符串

 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;

要获得一个随机字符,我们可以将字符视为向量,然后使用sample函数选择一个。我首先假设我需要搜索点,逗号或空格,然后使用gsub函数来替换所有这些?

2 个答案:

答案 0 :(得分:3)

鉴于你的澄清,试试这个:

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:"

答案 1 :(得分:2)

以下是chartr

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

数据

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