前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言_apply系列函数

R语言_apply系列函数

作者头像
用户1147754
发布2019-05-26 21:44:52
9420
发布2019-05-26 21:44:52
举报
文章被收录于专栏:YoungGyYoungGy
代码语言:javascript
复制
#apply
#get answer grouped by col/row
d = matrix(1:30,5,6)
apply(d,1,mean)  #row
apply(d,2,mean)  #col
M <- array( seq(32), dim = c(4,4,2))
apply(M, 1, sum) #row
apply(M, c(1,2), sum) #row % col
colMeans,rowMeans,colSums,rowSums

#lapply
#list to list
x <- list(a = 1, b = 1:3, c = 10:100) 
lapply(x, FUN = length) 
lapply(x, FUN = sum) 

#sapply
#list to vector
x <- list(a = 1, b = 1:3, c = 10:100)
sapply(x, FUN = length) 
sapply(x, FUN = sum) 
sapply(1:5,function(x) rnorm(3,x))
sapply(1:5,function(x) matrix(x,2,2))
sapply(1:5,function(x) matrix(x,2,2), simplify = "array")

#vapply
#speed up the sapply
x <- list(a = 1, b = 1:3, c = 10:100)
#Note that since the advantage here is mainly speed, this
# example is only for illustration. We're telling R that
# everything returned by length() should be an integer of 
# length 1. 
vapply(x, FUN = length, FUN.VALUE = 0L) 

#mapply
#Sums the 1st elements, the 2nd elements, etc. 
mapply(sum, 1:5, 1:5, 1:5) 
[1]  3  6  9 12 15
#To do rep(1,4), rep(2,3), etc.
mapply(rep, 1:4, 4:1)   

#Map
#A wrapper to mapply with SIMPLIFY = FALSE, so it is guaranteed to return a list.
Map(sum, 1:5, 1:5, 1:5)

#rapply
#Append ! to string, otherwise increment
myFun <- function(x){
    if (is.character(x)){
        return(paste(x,"!",sep=""))
    }
    else{
        return(x + 1)
    }
}
#A nested list structure
l <- list(a = list(a1 = "Boo", b1 = 2, c1 = "Eeek"), 
          b = 3, c = "Yikes", 
          d = list(a2 = 1, b2 = list(a3 = "Hey", b3 = 5)))
#Result is named vector, coerced to character           
rapply(l,myFun)
#Result is a nested list like l, with values altered
rapply(l, myFun, how = "replace")

#tapply
x <- 1:20
y <- factor(rep(letters[1:5], each = 4))
tapply(x, y, sum)  

参考资料

stackoverflow

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年08月18日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考资料
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档