#4.4.1lapply()和sapply()的使用
#lapply list apply
lapply(list(1:3,25:29),median) #对列表应用中位数,返回的是列表
sapply(list(1:3,25:29),median)#如果可以转化为矩阵或向量形式
#4.4.2扩展案例:文本词汇索引
#字母顺序排序
alphawl <- function(wrdlst) {
nms <- names(wrdlst) # the words
sn <- sort(nms) # same words in alpha order
return(wrdlst[sn]) # return rearranged version
}
#词频排序函数
# orders the output of findwords() by word frequency
freqwl <- function(wrdlst) {
freqs <- sapply(wrdlst,length) # get word frequencies
return(wrdlst[order(freqs)])
}
#4.4.3扩展案例:鲍鱼数据
g=c("M","F","F","I","M","M","F")
lapply(c("M","F","I"),function(gender) which(g==gender))#返回的列表
4.5递归型列表
#列表可以是递归的,列表的组件也是列表
b=list(u=5,v=12)
c=list(w=3)
a=list(b,c)
a
length(a)
#c()函数中的可选参数recursive,是否把原列表压平
c(list(a=1,b=2,c=list(d=5,e=9)))
c(list(a=1,b=2,c=list(d=5,e=9)),recursive=T)