【问题标题】:Elementwise vector multiplication between all rows of two data frames / matrices两个数据帧/矩阵的所有行之间的元素向量乘法
【发布时间】:2016-10-19 20:21:48
【问题描述】:

我有一组模型,需要在不同的估计器级别为每个模型生成生存估计。我首先想创建我将平均的模型。

在这里,模型集由一个矩阵表示,其中列是在特定模型中可能会或可能不会找到的效果, 行是单独的模型,单元格值 (1/0) 打开或关闭值。

modset <- structure(list(A = c(1, 1), B = c(1, 1), C = c(1, 1), D = c(1, 
1), E = c(0, 1), F = c(1, 0)), .Names = c("A", "B", "C", "D", 
"E", "F"), row.names = c(2L, 4L), class = "data.frame")

我还创建了一个矩阵,它提供了运行每个模型所需的值。

estvals <- structure(list(int = c(1L, 1L, 1L, 1L), age = c(6L, 18L, 6L, 
18L), species = c(1L, 1L, 0L, 0L), Time = c(12L, 50L, 27L, 12L
), height = c(90L, 90L, 90L, 90L), LastNew = c(7L, 7L, 21L, 21L
)), .Names = c("int", "age", "species", "Time", "height", "LastNew"
), row.names = c(1L, 11L, 16L, 20L), class = "data.frame")

我现在需要做的是创建一个输出,它基本上是每行 estvals 乘以每行 modset 的结果。 在我上面的示例中,我会得到 8 行(每个 estval 记录有 2 条记录):

outs <- structure(list(int = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), age = c(6L, 
6L, 18L, 18L, 6L, 6L, 18L, 18L), species = c(1L, 1L, 1L, 1L, 
0L, 0L, 0L, 0L), Time = c(12L, 12L, 50L, 50L, 27L, 27L, 12L, 
12L), height = c(0L, 90L, 0L, 90L, 0L, 90L, 0L, 90L), LastNew = c(7L, 
0L, 7L, 0L, 21L, 0L, 21L, 0L)), .Names = c("int", "age", "species", 
"Time", "height", "LastNew"), class = "data.frame", row.names = c(NA, 
-8L))

我无法想出解决方案。我尝试在 apply() 或 sweep() 中设置一些东西,但似乎无法获得可以满足我要求的功能。

最终,我正在为 SE 生成无条件估计,以在模型平均后建立适当的置信区间。因此,上面的每个 estvals 都会生成各种场景下的生存估计值,这些估计值最终会以图形方式显示。

【问题讨论】:

    标签: r matrix dataframe matrix-multiplication


    【解决方案1】:

    我们可以使用

    n1 <- nrow(modset)
    n2 <- nrow(estvals)
    outs <- modset[rep(1:n1, times = n2), ] * estvals[rep(1:n2, each = n1), ]
    

    无论您有矩阵还是数据框,这都适用。我使用rep生成的索引也可以通过expand.grid获取。

    【讨论】:

    • 非常感谢!我知道必须有一种简单直接的方法来为循环索引事物,或者设置我设想的覆盖。这是完美的。
    猜你喜欢
    • 2021-08-24
    • 1970-01-01
    • 1970-01-01
    • 2011-12-13
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多