R,未知数量的向量/矩阵的成对乘积 [英] R, pair-wise product of unknown number of vectors/matrices

查看:49
本文介绍了R,未知数量的向量/矩阵的成对乘积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在基数 R 中制作可变数量的矩阵/向量的成对乘积.我只有这个丑陋的解决方案(丑陋的是 <<-),但直觉上认为存在更好的——也许是递归的——方式,或者甚至是一个函数.我需要 prod 的成对版本.

I want to make pair-wise products of variable numbers of matrices/vectors in base R. I only have this ugly solution (ugly is <<-) but intuitively think a nicer - maybe recursive - way exists, or perhaps even a function. I need a pair-wise version of prod.

f1 <- function(...) {
  input <- list(...)
  output <- input[[1]]
  sapply(2:length(input), function(m) output <<- output*input[[m]])
  return(output)
}

m1 <- matrix(1:6, ncol = 2)
m2 <- matrix(6:1, ncol = 2)
m3 <- 1/matrix(6:1, ncol = 2)

all(f1(m1,m2,m3) == m1*m2*m3) #[1] TRUE

推荐答案

使用 Reduce :

f1 <- function(...) {
  Reduce(`*`, list(...))
}

all(f1(m1,m2,m3) == m1*m2*m3)
#[1] TRUE

这篇关于R,未知数量的向量/矩阵的成对乘积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆