Search code examples
rlistfor-loopapplylapply

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

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.