【发布时间】:2018-12-04 19:23:24
【问题描述】:
我有一个 n 列和 m 行的矩阵以及一个 f 函数列表。每个函数取一行矩阵并返回一个值,p。
用 m 行矩阵生成 f 列的最佳方法是什么?
目前我正在这样做:
# create a random 5x5 matrix
m <- matrix(rexp(25, rate=.1), ncol=5)
# example functions, in reality more complex but with the same signature
fs <- list(function(xs) { return(mean(xs)) }, function(xs) { return(min(xs)) } )
# create a function which takes a function and applies it to each row of m
g <- function(f) { return(apply(m, 1, f)) }
# use lapply to make a call for each function in fs
# use do.call and cbind to reshape the output from a list of lists to a matrix
do.call("cbind", lapply(fs, g))
澄清编辑:上面的代码确实有效,但我想知道是否有更优雅的方法。
【问题讨论】:
-
你的预期输出是什么?
-
一个行数与m相同,列数与fs长度相同的矩阵,其中每个单元格是函数f在m行上的结果。
-
请在创建随机矩阵之前使用
set.seed(1234)(或任何其他数字)以重现与您相同的结果。
标签: r matrix functional-programming