R语言_apply系列函数

#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值