mercredi 26 octobre 2022

How do I replace NAs in a column with random participant codes created from a function?

I have hundreds of data points in a dataframe. Some, however, do not have a value for a certain column. I have successfully created a function to create the respective input, a random participant codes:

ParticipantCodeGenerator <- function(n=1, length=2)
{
  randomString <- c(1:n)                 
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, LETTERS),
                                    length, replace=TRUE),
                             collapse="")
  }
  return(randomString)
}

# create 5 codes with 7 symbols each
ParticipantCodeGenerator(5,7)

I managed to replace the NAs in the column but not every row has a different code. When running the function by itself, every code is different.

df$var[is.na(df$var)] <- sample(ParticipantCodeGenerator(sum(is.na(df$var)),7), replace = TRUE)



Aucun commentaire:

Enregistrer un commentaire