# What's a good approach to teaching R in a computer lab?

There have been several good questions and sets of answers on introductory books or approaches to learning R eg here and here. But I have a slightly different problem - the best way to run an hour long session (or several such sessions) in a computer lab that will get people started in R, familiar with its basic approach etc.

My current plan would be to effectively work through the introductory chapter/s of something like Verzani's SimpleR and then introduce a familiar dataset, but is there any other approach that people have found useful? For example, is it good to introduce real data straight away, or address issues in more abstract way? Should I exhaustively go through how to use the square brackets, or excite people with examples of lattice graphics?

My target audience are familiar with statistics (although not experts) and competent SPSS users; not familiar with programming languages beyond the sort of macro and scripting you'd get in SPSS and similar things.

Any tips or references to lessons plans would be appreciated. However, I don't want to duplicate the many good lists of on-line material introducing R - strictly references to the face to face instructional question.

-
Probably should be a community wiki, right? – Peter Ellis Jan 31 '12 at 23:46
Sounds like a good idea to me. :) – Michelle Feb 1 '12 at 0:08
What's really crucial to how this question should be answered is what your setup will be. If you have a single "hour long session... in a computer lab" there is going to be very little you can do and you will have very few converts. If you have "several such" and they already know stats and basic programming fairly thoroughly, you can prime the pump such that they could move forward on their own and be enthusiastic about trying, but this latter requires a different approach. For people with some stats and no programming knowledge, a semester-long course would be ideal. – gung Feb 1 '12 at 3:07
Hmm, good point @gung, ok, the setup is quite specific. I am their manager and so could just tell them what to do. We have an fortnightly hour long session on stats skills (several of us take turns presenting) which is getting much more practical and we've agreed to do much of that in the lab on machines with real data. So I should have specified that the real requirement is to get them familiar enough with R in one or two sessions that when we do things like fitting regression models or looking at diagnostic plots in subsequent sessions we won't be completely distracted by basics. – Peter Ellis Feb 1 '12 at 4:26
@gung A big +1 for your thorough comment. I've been teaching R for a long and I finally came to similar conclusion: people having no lightweight understanding of programming or a command-line prompt will likely face some difficulties dealing with R. It gets worse when we have to make students familiar with statistics using R in few hours... – chl Feb 1 '12 at 21:26

I'd argue for a completely different approach. I've seen R tutorials that were taught from two different perspectives: a building-blocks approach, in which users are introduced to R's fundamental concepts, and a shock-and-awe approach, in which users are shown R's amazing capabilities but left with relatively little understanding of how to do anything. The latter definitely resonates more strongly with the pupils, but neither one seems very effective at actually producing users.

Instead, I would take a common and relatively simple task in SPSS and walk through converting it to R, with a little bit of feigned naivete on your part - e.g., following Xi'an's excellent suggestion to look up some desired functions with ?? rather than just recalling the right function from memory. Your newbies will almost certainly be converting existing processes as they learn R, not writing them from scratch - so why not show them exactly how you'd go about that?

A good example could consist of just loading data, performing some descriptives, and popping out some basic plots. lm() can be very, very simple and produces results they'll understand and can compare to SPSS output, so that might also good to cover.

For homework, get them to take a stab at converting one of their simple processes or loading and exploring a dataset with which they're very familiar. Give them some one-on-one time to figure out where things are going wrong, then cover those in the next session with more example conversions. Concepts from your list will inevitably come up (my bet: factors vs. character vectors, for vs. apply) - and then you'll have a real-world motivation for covering them. If they don't come up (attach), then they're not really needed yet - if that means your newbies write a little non-idiomatic code early on (for instead of apply), I don't see the harm.

This way, your students can progress in much the same way foreign-language students do (or at least, the way I did): crude translation of simple expressions prompts the desire for more complex expressions, which causes desire for a deeper understanding of grammar, which eventually leads to idiomatic expression. Don't jump to "grammar" too soon, and don't worry too much about teaching them things they aren't asking about because they'll probably just forget it anyway. Gentle pointers about idiomatic expression are great (for vs apply), but the main thing is to get them generating output and exploring on their own.

-
(+1) Thanks, Matt, that sounds like great advices. I especially like the last two paragraphs. – chl Feb 1 '12 at 21:32
Thanks Matt (and everyone else - all excellent help). I'll definitely be using the ?? approach, and getting them to recreate in the lab and as homework common tasks they do with other software (SPSS and Harmoni, which is basically a cross-tab package). I still need something reasonably directive just to get them opening the thing up and knowing where to start (and I've modified my lesson 1 plan accordingly) but I think motivating self-learning outside the lab is definitely the way to go. – Peter Ellis Feb 1 '12 at 21:37

OK, here's my own answer so far on what I think would get people started and motivate them to learn some more (I am trying to wean them off SPSS, which literally cannot do some of what we need to eg complex survey analysis, at least without buying more modules which I refuse to do).

At the end of the first session you should be able to:

Basics

• Use the interface to do straightforward calculations (use R as a calculator)
• Start, save and load a script window and use it efficiently
• Create and remove objects in your workspace
• See which folder is your working folder
• Understand how the P:/R/yourid folder works and what saving a workspace on exit does
• Load an image of a workspace including of XXX (our commonly used data)
• List the objects in memory
• List the names of columns (variables) in a data frame
• Print an object to the screen
• Attach and detach a data frame
• Know what is meant by: object, function, argument (to a function), workspace, vector, data frame, matrix, numeric, factor
• Know how to look up for help on a function
• Use ?? to find a list of relevant functions
• Where to go on the web and our local books and LAN for more resources
• understand enough of R basics to participate in lab sessions on specific statistical techniques

Data manipulation

• Create a vector of numbers using the : operator
• Do a table of counts for one variable
• Do a crosstab of counts for two variables
• Create a new object (eg one of the tables above) for further manipulation
• Transpose a matrix or table
• Create a vector of means of a continuous variable by a factor using tapply()
• Bind several vectors together using cbind() or data.frame()
• Create a subset of a matrix using the []
• Create a simple transformation eg logarithm or square root

Statistics

• Calculate the correlation of two continuous variables

Graphics

• Create a histogram of a continuous variable
• Create a graphics window and divide it into 2 or 4 parts
• Create a density line plot of a continuous variable
• Create a scatterplot of two continuous variables
• Add a straight line to a scatterplot (vertical, horizontal or a-b)
• Create labels for axes and titles

At the end of three sessions and doing a range of exercises inbetween you should also be able to:

Basics

• Import data in SPSS or .csv format
• Remove all the objects in your workspace to start fresh
• use a library of packages
• Save a workspace image and understand basic principles R and memory
• Generate random variables
• Use c() to create a vector
• Have a good feel for where to go to learn new methods and techniques

Data manipulation

• Use aggregate() on a real data set eg visitor arrivals numbers by month and country
• The ==, != and %in% operators; logical vectors; and using them to subset data
• ifelse() and using it to create new variables
• max, min and similar functions and how they work with vectors
• Create a vector or matrix to store numerous results
• Use a loop to repeat a similar function many times
• Use apply() to apply a function to each column or row of a matrix
• Create an ordered factor
• Use cut() to recode a numeric variable

Statistics

• Chi square test for a contingency table
• Robust versions of correlations
• Fit a linear model to two continuous variables, placing the results in an object and using anova(), summary() and plot() to look at the results
• understand enough about models and how they work in R to be ready to apply your skills to a wider range of model types
• Use boot() to perform bootstrap on a basic function like cor(), mean(), or var()
• Use sample() on a real life data set

Graphics

• Create a lattice density line plot of a continuous variable given different levels of a factor
• qqnorm
• build a scatter plot with different colour and character points showing different levels of a factor; add points or lines to an existing scatter plot
• dotcharts
• errbar()
• using a loop to draw multiple charts on a page
-
Given your setup, this seems reasonable, but is a lot to cover in an hour with newbies. I would constantly emphasize the resources available to them to build self-sufficiency. Specifically, go over the R manual that comes with the installation and the use of the help files. E.g., to introduce correlation start with ??correlation, show how to search the list, then ?cor and show how to read & understand the help; teach cor, hist, etc. from the documentation. No matter how smart they are, there's a limit with just one hour--they need to learn to get the info & troubleshoot by themselves. – gung Feb 1 '12 at 5:26
I think I work about 10 minutes walk from you, so give me a yell if you want to go over anything over a coffee. :) – Michelle Feb 1 '12 at 5:33
I don't think it's primarily the what, it's the how. It is about getting the pupils to learn stuff partly on their own and to have a comprehensive cheat sheet on hand + some home assignments. – Ondrej Feb 1 '12 at 8:06
@Michelle - sounds good, email me at peter.ellis [at] med.govt.nz – Peter Ellis Feb 1 '12 at 19:36
This is an amazingly ambitious list! I can't imagine you covering all of this in three hours - I don't think I'd even be able to say the words to cover all of this in three hours, much less answer questions. There are a few concepts I'd skip entirely: workspaces (I prefer not to use them - regenerating everything from script makes code more robust), attach (also problematic, especially for new users who don't understand environments), transposing (trivial to look up when you need it), and cbind (I almost never use this). – Matt Parker Feb 1 '12 at 21:19

To Peter's list I would add:

1. subset data frames: subset by observation (e.g. all responses above 3), subset by variable.
2. use ifelse statements (this was a huge learning curve for me, I kept trying to use the type of if statement), particularly nested ifelse.
3. summarise data into a smaller data frame by using the aggregate command.
4. learning to use the == operator.
5. using <- rather than =
6. rename variables
7. basic vectorization traps, such as max(A,B) in SAS does not do what max(A,B) does in R, if A is a variable in a data frame and B is a single value. To do the equivalent of the SAS code (and probably the SPSS code), I use an ifelse statement.
8. use with instead of attach. :)

More thoughts: They probably use COMPUTE a lot in SPSS, so covering how to do that in R would be good. Also, how to RECODE variables in R. When I was using SPSS I think most of my "non analysis" work was using those two commands.

-
Have a look on pmax... – Elvis Feb 1 '12 at 7:20
@Xi'an, going there now to have a peek (or a poke!) Ah, I hadn't clicked that was you, I had gone to your blog a couple of times via R-blogger links. :) – Michelle Feb 1 '12 at 8:09
When covering ifelse be SURE to show them how it works and what the warning in its documentation means. It works logically once you think about it, but I've seen total confusion about ifelse "changing" variable types and causing a lot of lost time. – Wayne Feb 1 '12 at 20:08
@Xi'an: The R help says, "the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions." I can think of situations other than mentioned in your blog, though so far only C-ish things like: a <- 1:5 ; b <- 4 ; a[b = 3] ; b ; a[b <- 3] ; b where the subscripting gives the same results, but b is different (first time not changed, second time changed). The = was never meant to be assignment and should have never been changed to try to make R more palatable. Don't do it. – Wayne Feb 1 '12 at 20:19
@Elvis +1000 internets to you, that pmax works great. – Michelle Feb 1 '12 at 22:36