Are you playing Secret Santa? a R function

We’re playing Secret Santa in my family: you are giving a present to only one other person, and their identity is only known to you. You need to give them a handmade present or a present bought in a second-hand store. Well that last part is our own variation of the concept.

You might be playing Secret Santa in your lab.

Here is a little R function to sort the draw without anyone seeing the outcome, and without the need to involve an external participant. The only inputs are:

-a vector of names of participants; for example c(“Patrick”,”Nicole”,”Maria”,”Pablo”)

-the folder where you want the output files; for example “C:/Users/Maria/SecretSanta”

After you’ve run the function, send to each person the output file named after them.

The function:

secretsanta=function(names,directory){
chosen=names
for (i in 1:length(names)){
 if (names[i]%in% chosen){
 choice=sample(chosen[-which(chosen==names[i])],1)
 }else{
 choice=sample(chosen,1)
 }
 chosen=chosen[-which(chosen==choice)]
 write.table(paste(directory,"/",names[i],", you will give a present to ",choice,sep=""),
 file=paste(names[i],".txt",sep=""),quote=F,row.names=F,col.names=F)
 }
 return("Done! the files are in the provided directory. Merry Christmas.")
}

 

Load the function into R by entering the code above, and then run the function with your input:

secretsanta(names=c("Patrick","Nicole","Maria","Pablo"), directory="C:/Users/Maria/SecretSanta")

 

Merry Christmas!

 

Leave a Reply

Your email address will not be published.