samsmith
samsmith

Reputation: 85

R - replacement at random

The sub function in R is replacing the first occurence of a pattern.

Example:

> s <- "my name is sam"
> sub(" ","*",s)
[1] "my*name is sam"

However is there an easy way to replacement at a random position of the three spaces (" "):

"my*name is sam"
"my name is*sam"
"my name*is sam"

Upvotes: 0

Views: 34

Answers (3)

Damiano Fantini
Damiano Fantini

Reputation: 1975

A possible solution is provided here following. Briefly, you can split your sentence when a space is found. You use sample() to pick a random position and then replace the corresponding space with a character of your choice (*). Finally, you paste everything together.

s <- "my name is sam"

# get your words
elems <- strsplit(s, " ")[[1]]

# recreate the spaces between words. Add an extra "" to add after the last word 
spacer <- c(rep(" ", (length(elems)-1)), "") 

# pick a random 'space' and replace it to *
pos <- sample(1:(length(elems)-1), size = 1)
spacer[pos] <- "*"

# paste everything together
result <- paste(paste(elems, spacer, sep = "", collapse = ""), sep = "", collapse = "")

The result

result
"my name*is sam"

Run the same lines again a few times, the sampling is random, so you should get all three possible results...

Upvotes: 1

67342343
67342343

Reputation: 816

And using stringr:

library(stringr)
s <- "my name is sam"
index <- sample(str_locate_all(s, " ")[[1]][,1], 1)
str_sub(s, index, index) <- "*"

Upvotes: 1

G5W
G5W

Reputation: 37641

A different solution. Count the blanks and choose one to replace at random. Then construct a regular expression based on the randomly chosen spot. This code uses str_count from the stringr package.

library(stringr)
position = sample(1:str_count(s, ' '), 1) - 1
pattern = paste0("((\\S*\\s){", position, "}\\S*)\\s")
sub(pattern, "\\1*", s)

A note about the regular expression. It skips the first position blanks (and all non-blanks) to replace just the one chosen at random.

Upvotes: 0

Related Questions