R语言_apply系列函数

2019-05-26 21:44:52 浏览数 (4)

代码语言: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

1 人点赞