code examples from Hadley Wickham's book: Advanced R