coursera R Programming NOTE(6)

loop functions

lapply(list,function)
example:

x <- list(a = 1:5, b = rnorm(10)) 
lapply(x, mean)
 x <- list(a = 1:4, b = rnorm(10), c = rnorm(20, 1), d = rnorm(100, 5)) 
lapply(x, mean)
x <- 1:4
lapply(x, runif)  
x <- list(a = matrix(1:4, 2, 2), b = matrix(1:6, 3, 2)) 
lapply(x, function(elt) { elt[,1] })

sapply(list,function)
The sapply() function behaves similarly to lapply()

  • If the result is a list where every element is length 1, then a vector is returned
  • If the result is a list where every element is a vector of the same length (> 1), a matrix is returned.
  • If it can’t figure things out, a list is returned

tapply(vector,INDEX,function)

  • INDEX is a factor or a list of factors (or else they are coerced to factors)
    example:
x <- c(rnorm(10), runif(10), rnorm(10, 1)) 
 f <- gl(3, 10) 
 tapply(x, f, mean)

apply(array,dims,function)
example:

 x <- matrix(rnorm(200), 20, 10)
apply(x, 2, mean) ## Take the mean of each column
apply(x, 1, sum) ## Take the mean of each row 
x <- matrix(rnorm(200), 20, 10) 
apply(x, 1, quantile, probs = c(0.25, 0.75))
a <- array(rnorm(2 * 2 * 10), c(2, 2, 10)) 
apply(a, c(1, 2), mean) 

Col/RowSumsandMeans

rowSums = apply(x, 1, sum)
rowMeans = apply(x, 1, mean)
colSums = apply(x, 2, sum)
colMeans = apply(x, 2, mean)

mapply(function,argument1,argument2,argument3...)
example:

mapply(rep, 1:4, 4:1)
## "1:4" is the first argument of function "rep"
## "4:1" is the second argument of function "rep"

noise <- function(n, mean, sd) {  rnorm(n, mean, sd)  } 
mapply(noise, 1:5, 1:5, 2) 
## "1:5" is the first argument of function "noise"
## "1:5" is the second argument of function "noise"
## "2" is the third argument of function "noise"

split(vector or list or data frame,factor)
The split() function takes a vector or other objects and split sitin to groups determined by a factor or list of factors.
example:

 x <- c(rnorm(10), runif(10), rnorm(10, 1))
f <- gl(3, 10)
split(x, f) 
lapply(split(x, f), mean) 

library(datasets)
head(airquality) 
s <- split(airquality, airquality$Month) 
lapply(s, function(x) {  colMeans(x[, c("Ozone", "Solar.R", "Wind")])  }) 
sapply(s, function(x) {  colMeans(x[, c("Ozone", "Solar.R", "Wind")],  na.rm = TRUE) 

x <- rnorm(10)
f1 <- gl(2, 5)
f2 <- gl(5, 2) 
interaction(f1, f2)
str(split(x, list(f1, f2))) 
str(split(x, list(f1, f2), drop = TRUE)) 

你可能感兴趣的:(coursera R Programming NOTE(6))