noamross / zero-dependency-problems

Real-world code problems in R, without dependencies
79 stars 25 forks source link

apply-with-na #8

Open noamross opened 9 years ago

noamross commented 9 years ago

https://github.com/noamross/zero-dependency-problems/blob/master/R/apply-with-na.md

I have a data frame (tadlengths) with five columns of tadpole lengths for a bunch of different treatments. I want to average the five lengths. I did this by:

meanlength = apply(tadlengths, 1, mean)

However, sometimes I only had four lengths, so there are NAs in those rows. I want to average the four lengths on those rows, but the code above gives me "NA" for those rows. I feel like there is a very, very, easy solution for this, but I can't figure it out!

zmjones commented 8 years ago

I think the easiest way to teach this is to first show what the default behavior of mean is on a numeric vector with a NA. Then you could show how apply is a looping construct, so that the student learns to look at the function return object when they get output they didn't want. You could also use this to talk about anonymous functions.