【问题标题】:R: Converting a data frame of row/column indices to a matrixR:将行/列索引的数据框转换为矩阵
【发布时间】:2017-10-31 14:12:21
【问题描述】:

我想像这样转换一个对象

df <- data.frame(ROW = c(1,3),COLUMN =c(2,3),VALUE = c(10,20))
df
ROW COLUMN VALUE 
1        2    10
3        3    20

到这样的矩阵

m <-matrix(c(0,10,0,0,0,0,0,0,20),ncol = 3,nrow = 3)
m
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]   10    0    0
[3,]    0    0   20

我知道数据框代表一个稀疏矩阵,但我没有找到与我正在寻找的内容完全相关的任何其他问题。

【问题讨论】:

标签: r dataframe matrix


【解决方案1】:

我们可以使用sparseMatrix

library(Matrix)
as.matrix( sparseMatrix(i = df$COLUMN, j= df$ROW, x= df$VALUE))
#      [,1] [,2] [,3]
#[1,]    0    0    0
#[2,]   10    0    0
#[3,]    0    0   20

或者创建一个 0 的 matrix 然后赋值

m1 <- matrix(0, 3, 3)
m1[as.matrix(df[2:1])] <- df$VALUE

注意:根据输出,ROW/COLUMN 索引似乎是反转的

【讨论】:

  • replace(matrix(0, max(df$ROW), max(df$COLUMN)), as.matrix(df[c("ROW", "COLUMN")]), df$VALUE)
【解决方案2】:

我们可以遍历df的行,根据df中包含的行列索引填充一个矩阵:

# initialize
new_mat <- matrix(0, ncol = max(df$ROW), nrow = max(df$COLUMN))

for(i in 1:nrow(df)){
  new_mat[df[i,]$COLUMN, df[i,]$ROW] <- df[i,]$VALUE
}

#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]   10    0    0
# [3,]    0    0   20

正如@akrun 所指出的,行索引和列索引似乎被翻转了。

【讨论】:

    【解决方案3】:

    这是apply的解决方案

    mat <- matrix( 0, ncol = max(df$ROW), nrow = max(df$COLUMN) )
    f <- function( x ) { mat[x[1],x[2]] <<- x[3] }
    apply( df, 1, f } )
    

    &lt;&lt;- 运算符将该值应用于外部定义的垫子。 可能需要使用as.numeric等进行数据类型转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-24
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      相关资源
      最近更新 更多