Secret Santa in R

Secret Santa (Amigo Invisible in Spanish) is a Christmas tradition very common all around the world. In a group of friends they are assigned randomly a person to give a gift. The assignation is anonymous and there is a lot of ways to do the raffle. Here I want to show a possibility to do it with R. It’s very simple, and there is a infinity of alternatives. I hope you like it.

# Secret Santa

# List of names
names <- c("James", "Chris", "Mary", "Lisa", "Michelle", "John", "Daniel", "Sarah", "Carol", "Ruth")

# Initialization
FROM <- TO <- TRUE
n <- length(names)

while( sum(FROM==TO)>0 ){
 FROM <- sample(names, n)
 TO <- sample(names, n)
 secretSanta <- data.frame(FROM, TO)
}

And the result is…

> secretSanta
  FROM TO
1 John Michelle
2 Ruth John
3 Daniel Ruth
4 Carol James
5 Michelle Sarah
6 Chris Mary
7 Lisa Carol
8 Mary Lisa
9 James Daniel
10 Sarah Chris

We need to insert a loop to avoid assigning one person himself. A simple alternative is to generate a sample of names and assign directly each name to the next, first to second, second to third, and so on. It is clearer to understand this way, and we can afford to waste computing capacity for this algorithm. Finally, we plot the results with ggplot.

secretSantaStacked <- data.frame(names = c(FROM, TO), 
 type = c(rep(c("FROM","TO"),each=n)),
 id=rep(1:n,2))

ggplot(secretSantaStacked, aes(type, names, group=id, colour=names))+
 geom_path(size=2, alpha=0.5) + geom_point(size=3)

secretsanta

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s