I have 20 models (1:20) and 2 samples per model. I want to write a function in R that will take Model# and Sample# as input and output 40 unique random codes across samples for a Model and print the output like this. In addition, I would also like to have the option to add extra columns(if needed) of non repeated random codes like this and extra model numbers.
So far I have this code which gives me this output
food_safety_lot_codes <- function(random_seed = NULL,
number_of_cus,
number_of_samples,
file = NULL){
library(tidyverse)
if(!is.null(random_seed)){
set.seed(random_seed)
}
else{
random_seed <- round(runif(1) * 1000000, 0)
print(paste("Your unique starting seed:", random_seed))
set.seed(random_seed)
}
if((number_of_cus*number_of_samples) <= 899){
digits <- 3
digit_codes <- 100:999
}
else if((number_of_cus*number_of_samples) > 899 &
(number_of_cus*number_of_samples) <= 8999){
digits <- 4
digit_codes <- 1000:9999
}
else if((number_of_cus*number_of_samples) > 8999 &
(number_of_cus*number_of_samples) <= 89999){
digits <- 5
digit_codes <- 10000:99999
}
else{
digits <- 0
print("You have requested too many codes.")
}
if(digits != 0){
random_order <- runif(length(digit_codes))
codes.df <- as.data.frame(cbind(digit_codes, random_order)) %>%
arrange(random_order)
codes.df <- codes.df[1:(number_of_cus*number_of_samples),]
CU <- rep(1:number_of_cus, each = number_of_samples)
Sample <- rep(1:number_of_samples, number_of_cus)
codes.df$CU <- CU
codes.df$Sample <- Sample
codes.df <- codes.df %>%
rename(`Random Codes` = digit_codes) %>%
select(CU, `Random Codes`, Sample)
if(!is.null(file)){
filename <- file
}
else{
filename <- paste("labels (", digits,
" digits).csv",
sep = "")
}
write.csv(codes.df,
filename,
row.names = FALSE)
print(paste("There is now a .csv file in this directory:",
getwd()))
}
}
How can I do the additional part? I would highly appreciate any help. Thanks!
Aucun commentaire:
Enregistrer un commentaire