我想体验一下 R 中的函数式编程。 为此,我想写vandermonde matrix计算,因为它可能涉及一些构造。
在命令式风格中,这将是:
vandermonde.direct <- function (alpha, n)
{
if (!is.vector(alpha)) stop("argument alpha is not a vector")
if (!is.numeric(alpha)) stop("argument n is not a numeric vector")
m <- length(alpha)
V <- matrix(0, nrow = m, ncol = n)
V[, 1] <- rep(1, m)
j <- 2
while (j <= n) {
V[, j] <- alpha^(j - 1)
j <- j + 1
}
return(V)
}
你会如何在 R 中以函数式风格优雅地编写它?
以下方法不起作用:
x10 <- runif(10)
n <- 3
Reduce(cbind, aaply(seq_len(n-1),1, function (i) { function (x) {x**i}}), matrix(1,length(x10),1))
正如它告诉我的那样Error: Results must have one or more dimensions.
对于来自 i in seq_len(3-1)
的函数列表到函数x -> x**i.
最佳答案
使用Reduce
来完成此任务似乎不太自然。
该错误消息是由 aaply
引起的,它尝试返回一个数组:
你可以使用alply
来代替;您还需要在某个地方调用您的函数。
以下是一些惯用的替代方案:
outer( x10, 0:n, `^` )
t(sapply( x10, function(u) u^(0:n) ))
sapply( 0:3, function(k) x10^k )
关于r - R 中的函数式编程 : illustration with vandermonde matrix,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17525841/