【问题标题】:Filling a matrix from a dataframe with separate functions for diagonal and off-diagonal elements使用对角线和非对角线元素的单独函数从数据框中填充矩阵
【发布时间】:2015-06-05 12:13:28
【问题描述】:

我有以下问题,我有一个数据框 (df):

df <- data.frame(inp = c("inp1", "inp2", "inp3"), A = c(1,2,3), B = c(1,2,3))

我需要从这个数据帧构造一个 inp*inp 方阵,它符合对角线和非对角线元素的某些公式。

对角元素计算为 M[i,i] = A[i,i]^2 + B[i,i] 非对角元素计算为 M[i,j] = A[i]* A[j] 其中 i,j 属于集合 (inp1, inp2, inp3)。

这就是我到目前为止所得到的——计算非对角线值的函数仍然让我无法理解。

 matFun <- function(df){
       x <- matrix(,
                   nrow = nrow(df),
                   ncol = nrow(df),
                   dimnames = list(df$inp, df$inp))

 #funOffDiag <- ???

 funDiag <- function(A,B){A^2 + B}
 d <- apply(df[c("A","B")], 1, function(y) funDiag(y["A"],y["B"]))
 diag(x) <- d
 x
 }

 matFun(df)

我需要这个解决方案作为一个函数,因为我必须将它应用到一个较长的数据帧列表中。

【问题讨论】:

    标签: r matrix dataframe


    【解决方案1】:
    df <- data.frame(inp = c("inp1", "inp2", "inp3"), A = c(1,2,3), B = c(1,2,3))
    mat <- tcrossprod(df$A)
    colnames(mat) <- rownames(mat) <- df$inp
    diag(mat) <- diag(mat) + df$B
    #     inp1 inp2 inp3
    #inp1    2    2    3
    #inp2    2    6    6
    #inp3    3    6   12
    

    你应该可以自己创建一个函数...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2014-01-06
      • 2020-02-18
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多