12.07.2015 Views

R dummies

R dummies

R dummies

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Applying functions on rows and columnsIn Chapter 7, you calculate the sum of a matrix with the rowSums() function.You can do the same for means with the rowMeans() function, and you have therelated functions colSums() and colMeans() to calculate the sum and the mean foreach column. But R doesn’t have similar functions for every operation you want tocarry out. Luckily, you can use the apply() function to apply a function over everyrow or column of a matrix or data frame.Counting birdsImagine you counted the birds in your backyard on three different days andstored the counts in a matrix like this:> counts colnames(counts) countssparrow dove crow[1,] 3 6 8[2,] 2 5 6[3,] 4 1 1Each column represents a different species, and each row represents adifferent day. Now you want to know the maximum count per species on any givenday. You could construct a for loop to do so, but using apply(), you do this in onlyone line of code:> apply(counts, 2, max)sparrow dove crow4 6 8The apply() function returns a vector with the maximum for each column andconveniently uses the column names as names for this vector as well. If R doesn’tfind names for the dimension over which apply() runs, it returns an unnamedobject instead.Let’s take a look at how this apply() function works. In the previous lines ofcode, you used three arguments:The object on which the function has to be applied: In this case, it’s thematrix counts.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!