【问题标题】:R: iterate through list of coordinates (indices) to find entries in matrixR:遍历坐标(索引)列表以查找矩阵中的条目
【发布时间】:2020-11-05 11:43:03
【问题描述】:

我有一个名为coordinates 的矩阵,它告诉我在另一个名为data 的矩阵中的哪里可以找到我想要的条目。例如:

set.seed(0)
coordinates <- matrix(c(1, 2, 
                        5, 3, 
                        4, 3), 
                       nrow = 2)
rownames(coordinates) <- c("x","y") # optional - I added this clarity
data <- matrix(rbinom(25, 1, 0.5), 5) # makes a 5x5 matrix of 1's and 0's

我想要一个函数来返回位于这些坐标处的条目的总和。在这种情况下:

data[1,2] + data[5,3] + data[4,3]

我假设有一些巧妙地使用 map、Map 或 apply 系列可以简洁地完成此任务?我愿意使用 data.table、tidyverse 等以及将coordinates 转换为其他形式。

【问题讨论】:

    标签: r matrix dplyr data.table apply


    【解决方案1】:

    我们可以提取具有行/列索引的元素,然后在提取的元素上使用sum

    sum(data[cbind(c(1, 5, 4), c(2, 3, 3))])
    

    或者通过cbind第一行和第二行将“坐标”转换为两列矩阵

    sum(data[cbind(coordinates[1,], coordinates[2,])])
    

    或者如 cmets 中提到的 @markus

    sum(data[t(coordinates)])
    

    【讨论】:

      猜你喜欢
      • 2017-08-04
      • 2019-08-28
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      相关资源
      最近更新 更多