示例:
str(apply) # str能以简洁的方式列出函数
# 运行结果:
# function (x, MARGIN, FUN, …)
x <- matrix(1:20,ncol=4) # 创建一个五行四列的矩阵
x
# 运行结果:
# [,1] [,2] [,3] [,4]
# [1,] 1 6 11 16
# [2,] 2 7 12 17
# [3,] 3 8 13 18
# [4,] 4 9 14 19
# [5,] 5 10 15 20
apply(x,1,mean) # 对行进行操作
# 运行结果:
# [1] 8.5 9.5 10.5 11.5 12.5
apply(x,2,mean) # 对列进行操作
# 运行结果:
# [1] 3 8 13 18
str(lapply) # str能以简洁的方式列出函数
# 运行结果:
# function (x, FUN, …)
x <- list(a=1:5,b=exp(0:3))
x
# 运行结果:
# $a
# [1] 1 2 3 4 5
#
# $b
# [1] 1.000000 2.718282 7.389056 20.085537
#
lapply(x,mean)
# 运行结果:
# $a
# [1] 3
#
# $b
# [1] 7.798219
#
str(sapply) # str能以简洁的方式列出函数
# 运行结果:
# function (X, FUN, …, simplify = TRUE, USE.NAMES = TRUE)
list <- list(c("a","b","c"),c("A","B","C"))
list
# 运行结果:
# [[1]]
# [1] "a" "b" "c"
#
# [[2]]
# [1] "A" "B" "C"
#
sapply(list,paste,1:3,simplify=TRUE)
# 运行结果:
# [,1] [,2]
# [1,] "a 1" "A 1"
# [2,] "b 2" "B 2"
# [3,] "c 3" "C 3"
sapply(list,paste,1:3,simplify=FALSE)
# 运行结果:
# [[1]]
# [1] "a 1" "b 2" "c 3"
#
# [[2]]
# [1] "A 1" "B 2" "C 3"
#
str(tapply) # str能以简洁的方式列出函数
# 运行结果:
# function (X, INDEX, FUN = NULL, …, default = NA, simplify = TRUE)
height <- c(174,164,180,171,160)
sex <- c("F","F","M","F","M")
tapply(height,sex,mean)
# 运行结果:
# F M
# 169.6667 170.0000
str(mapply) # str能以简洁的方式列出函数
# 运行结果:
# function (FUN, ..., MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)
mapply(rep,times=1:3,MoreArgs=list(x=1:2))
# 运行结果:
# [[1]]
# [1] 1 2
#
# [[2]]
# [1] 1 2 1 2
#
# [[3]]
# [1] 1 2 1 2 1 2
mapply(rep,times=c(2,2),MoreArgs=list(x=1:2))
# 运行结果:
# [,1] [,2]
# [1,] 1 1
# [2,] 2 2
# [3,] 1 1
# [4,] 2 2