Skip to content

Instantly share code, notes, and snippets.

@geofferyzh
Created April 17, 2012 14:41
Show Gist options
  • Save geofferyzh/2406417 to your computer and use it in GitHub Desktop.
Save geofferyzh/2406417 to your computer and use it in GitHub Desktop.
RinAction - R Functions - Applying Functions to R Objects
###################################################
### Apply Functions to Matrices and Data Frames ###
###################################################
# One of the interesting features of R functions is that they can be applied to a variety of
# data objects (scalars, vectors, matrices, arrays, and data frames).
b <- c(1.243, 5.654, 2.99)
round(b)
c <- matrix(runif(12), nrow=3)
c
log(c)
mean(c)
# Apply functions to any dimensions of an object using the apply() function
mydata <- matrix(rnorm(30), nrow=6)
mydata
apply(mydata, 1, mean) # calculate row mean
apply(mydata, 2, mean) # calculate column mean of the matrix
apply(mydata, 2, mean, trim=.2) # calculate trimmed mean based on the middle 60% of data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment