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)) 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,106评论 0 23
  • 秦马,那么辣 2015-06-05 忽然发现自己过了对跑步的热恋期了,具体表现在就是近几次跑完比赛,每次都是磨磨蹭...
    半个错别字阅读 372评论 0 1
  • 我们终究要凭借自身努力才能过上有安全感的生活,包括有情趣的爱情和有温暖的婚姻。越努力越幸运,越美丽越安全。 就算我...
    活简阅读 955评论 0 0
  • 秋雨漫漫,也是寂寞。 轻柔如落花,温婉如诗意。 捧平仄心事,端坐风口。 时光如水轮回。 听...
    采薇cc阅读 178评论 0 0
  • 书法名家刘哥算是我家的常客了,我和刘哥是很能合得来的忘年交。由于家住的很近,几乎是一墙之隔。往来相对是很方便的。刘...
    城里打铁的阅读 155评论 0 0