Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using lapply to replace values in a list from randomly sampled values from another list

I am trying to replace values in a list word, on indexes specified by the list positions, by sampling values that exist in a third list called letters.

Here’s an example of how my lists look like:

word <- c("A","E","C","A","R","O","P")

positions <- c(1,5,3,7)

letters <- c("A","B","C","D","E","F")

One important detail is that the value in word[position] should not remain the same after sampling, which can happen because of overlapping values in letters and word

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The current code that I am using to do this is:

for (i in 1:length(positions)){
  temp <- word[[positions[i]]] 
  word[[positions[i]]] <- sample(letters, 1)
  while (word[[positions[i]]] == temp) {
    word[[positions[i]]] <- sample(letters, 1) 
  }
}

While this works, I realize that it’s extremely inefficient, as the order in which I change the values in the list doesn’t matter. I’ve been trying to use of of the "apply" family of functions to solve this, but I am having trouble figuring out a solution.

Thank you very much for the attention!

>Solution :

You can do this:

word[positions] <- sapply(word[positions], 
                          \(w) sample(setdiff(letters, w), 1))

Inside sapply you always remove the current word from letters, therefore a different one is guaranteed to be sampled.

Also note that letters is a built-in R constant (containing lowercase english alphabet, see ?letters) so it is generally not a good idea to use this name for user-defined variables.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading