【问题标题】:Iterate over columns of a matrix in R迭代R中矩阵的列
【发布时间】:2019-09-20 16:17:17
【问题描述】:

我有一个函数

function (x, y) { ... }

它需要两个向量 xy 并返回从它们计算的值。

我想将此函数成对应用于两个矩阵xsys 的列向量。从R, iterating over the row vectors of a matrix 我发现mapply() 但这似乎将函数成对应用于矩阵的每个元素。相反,我想将该函数应用于整个列。我该怎么做?

为了澄清,这里是一个人为的例子:

xs <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2)
ys <- matrix(c(25, 26, 27, 28, 29, 30), nrow = 3, ncol = 2)
dot <- function(x, y) sum(x*y)

【问题讨论】:

  • 多一点上下文(最好是minimal reproducible example)会有所帮助。请注意,如果情况变得更糟,您可以转置两个矩阵,然后遍历行。
  • @JohnColeman 我正在努力。我用一个人为的例子编辑了这个问题。不过,我对 R 的了解不足,无法填写 dot 函数的详细信息。
  • dot 将只是 dot &lt;- function(x,y) sum(x*y)(如果尚未内置)
  • @JohnColeman 有道理。这是一个微不足道的细节,对我的问题并不重要。但它使问题更具体,更容易理解。
  • 那么你想要的输出是什么?你想要它作为一个矩阵吗?

标签: r matrix


【解决方案1】:

还没有人提到asplit(在 R 3.6.0 中添加) - 专门为此案例制作的函数。

例子:

mapply(dot, asplit(xs, 2), asplit(ys, 2))

相同但使用行:

mapply(dot, asplit(xs, 1), asplit(ys, 1))

【讨论】:

    【解决方案2】:

    这是一种方法:

    xs <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2)
    ys <- matrix(c(25, 26, 27, 28, 29, 30), nrow = 3, ncol = 2)
    dot <- function(x, y) {
      sum(x*y)
    }
    
    dots <- sapply(1:ncol(xs),function(i) dot(xs[,i],ys[,i])) #dots = c(158, 437)
    

    【讨论】:

      【解决方案3】:

      使用简单的for 循环

      v1 <- numeric(ncol(xs))
      for(i in seq_along(v1)) v1[i] <- dot(xs[,i], ys[,i])
      v1
      #[1] 158 437
      

      或使用矢量化选项

      colSums(xs * ys)
      #[1] 158 437
      

      【讨论】:

      • 你的第二个例子解决了计算列向量点积的具体问题。但这只是一个人为的例子,所以对于将函数应用于列对的更一般的问题没有帮助。
      【解决方案4】:

      映射期望列表或数据框在列上工作:

      mapply(dot,as.data.frame(xs),as.data.frame(ys))
      
       V1  V2 
      158 437
      

      【讨论】:

        【解决方案5】:

        你也可以像这样使用mapply

        mapply(function(i, x = xs, y = ys) dot(x[,i],y[,i]), 1:ncol(xs))
        

        或使用purrr:

        purrr::map_dbl(1:ncol(xs), function(i,x,y) dot(x[,i],y[,i]), x = xs, y = ys)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-15
          • 1970-01-01
          • 1970-01-01
          • 2017-03-22
          • 1970-01-01
          相关资源
          最近更新 更多