vendredi 1 janvier 2021

R: How to create a df with columns of random strings

I have a df, I would like one of the colums to contain a string of 5 random values between 1 and 100:

expected_df <- data.frame("x" = stri_rand_strings(4, 8), "y" = round(runif(4, 13, 272)), z =(c('2 3 50 17 9', '10 3 5 100 22', '86 30 74 10 27', '6 33 4 19 66')))

I have tried to create a function that repeat '1-100' 5 times, however it repeats the same 5 numbers for each row in the df


rand_str<- function() {
  x = c(sample(1:100, 5, replace = FALSE))
  return(paste0(x,collapse = " "))
}

df <- data.frame("x" = stri_rand_strings(4, 8), "y" = round(runif(4, 13, 272)), z =rep(rand_str(),4))  

I have tried to add rep(rand_str(),4), however it doesn't solve the problem.

How can I create 4 rows with 5 different digits in each?

Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire