3
我有一個矩陣列表,我試圖將函數應用於每個矩陣的每一列。自然的方式來做到這一點,我想,就是窩apply
在lapply
,但是當我這樣做,它給了我一個錯誤:嵌套適用於lapply循環列矩陣的列
library(hydroGOF) # for the mse function
# Create a vector for comparison
A <- rnorm(10)
# Create a list of matrices to be looped over
B <- rnorm(10 * 5 * 3)
list.element.number <- rep(1:3, 50)
B.list <- split(B, list.element.number)
B.list <- lapply(B.list, matrix, ncol = 5, nrow = 10) # A 3 element list of 10 x 5 matrices
# Wrapper function for mse
my.mse <- function(sim) {
mse(sim, A)
}
# I'm trying to loop through each column of B.list and compare it to A
lapply(B.list, apply, MARGIN = 2, FUN = my.mse)
# Error in FUN(X[[1L]], ...) :
# unused arguments (function (X, MARGIN, FUN, ...)
# {
# FUN <- match.fun(FUN)
# dl <- length(dim(X))
# if (!dl) stop("dim(X) must have a positive length")
# if (is.object(X)) X <- if (dl == 2) as.matrix(X) else as.array(X)
# d <- dim(X)
# dn <- dimnames(X)
# ds <- seq_len(dl)
# if (is.character(MARGIN)) {
# if (is.null(dnn <- names(dn))) stop("'X' must have named dimnames")
# MARGIN <- match(MARGIN, dnn)
# if (anyNA(MARGIN)) stop("not all elements of 'MARGIN' are names of dimensions")
# }
# s.call <- ds[-MARGIN]
# s.ans <- ds[MARGIN]
# d.call <- d[-MARGIN]
# d.ans <- d[MARGIN]
# dn.call <- dn[-MARGIN]
# dn.ans <- dn[MARGIN]
# d2 <- prod(d.ans)
# if (d2 == 0) {
# newX <- array(vector(typeof(X), 1), dim = c(prod(d.call), 1))
# ans <- FUN(if (length(d.call) < 2) newX[, 1] else array(newX[, 1], d.call, dn.call), ...)
# return(if (is.null(ans)) ans else if (length(d.ans) < 2) ans[1][-1] else array(ans, d.ans, dn.a
理想的情況下,這會給我一個3元素列表,其中每個元素都是一個5元素的向量,但是我得到一個錯誤。有誰知道如何解決這個問題(除了for
循環,感覺不雅),或者出了什麼問題?
位置參數應該工作,但:lapply(B.list,apply,2,my.mse)'。 – 2015-02-24 20:55:03
@KonradRudolph,很棒的主意,但顯然你必須在那裏小心謹慎。 – BrodieG 2015-02-24 20:56:03