【问题标题】:converting rows to columns to create a matrix将行转换为列以创建矩阵
【发布时间】:2016-09-03 01:05:35
【问题描述】:

我有以下形式的数据,我想根据这些数据创建一个矩阵。

 B<- c('nancy','bill','bob','badri','bill')
 c<- c('martial-arts','dance','sports','judo','judo')

  df<- data.frame(B,C)

我想创建一个矩阵,该矩阵属于哪个组,并且用户为 row.names。任何人都可以有任何建议吗?

    user martial-arts dance sports judo 
    nancy      1         0      0    0
    bill       0         1      0    1
    bob        0         0      1    0
    badri      0         0      0    1

【问题讨论】:

  • 看起来with(df, as.matrix(table(B, C))) 可能会这样做。
  • reshape2::dcast(df, B ~ C, fun = length),这可能更适合大数据但返回数据框。
  • xtabs(count ~ ., transform(df, count=1) ) 也是如此。

标签: r dplyr reshape2 tapply


【解决方案1】:

可能是这样的:

x <- c('nancy','bill','bob','badri','bill')
y <- c('martial-arts','dance','sports','judo','judo')

x0 <- unique(x); y0 <- unique(y)
mat <- matrix(0L, length(x0), length(y0), dimnames = list(x0, y0))
mat[cbind(match(x, x0), match(y, y0))] <- 1L

#      martial-arts dance sports judo
#nancy            1     0      0    0
#bill             0     1      0    1
#bob              0     0      1    0
#badri            0     0      0    1

我使用了矩阵索引:

  • match(x, x0) 给出行索引;
  • match(y, y0) 给出列索引;
  • cbind(match(x, x0), match(y, y0)) 给出 1 所在的矩阵索引。

如果您知道生成的矩阵中的零比一多得多,您可以构造一个稀疏矩阵:

library(Matrix)
sparseMatrix(i = match(x, x0), j = match(y, y0), x = 1, dimnames = list(x0, y0))

#4 x 4 sparse Matrix of class "dgCMatrix"
#      martial-arts dance sports judo
#nancy            1     .      .    .
#bill             .     1      .    1
#bob              .     .      1    .
#badri            .     .      .    1

@thelatemail 的替代方案:

## coding to factor with desired order of levels is necessary
x <- factor(x, levels = x0)
y <- factor(y, levels = y0)

## dense matrix
xtabs(~ x + y)

#       y
#x       martial-arts dance sports judo
#  nancy            1     0      0    0
#  bill             0     1      0    1
#  bob              0     0      1    0
#  badri            0     0      0    1

## sparse matrix
xtabs(~ x + y, sparse = TRUE)

#4 x 4 sparse Matrix of class "dgCMatrix"
#      martial-arts dance sports judo
#nancy            1     .      .    .
#bill             .     1      .    1
#bob              .     .      1    .
#badri            .     .      .    1

【讨论】:

  • 我们可以创建带有 id 值的矩阵来进行网络分析吗?像用户的 u1、u2、u3 和组的 g1、g2、g3 一样?非常感谢!
  • 是的,我做到了:)
猜你喜欢
  • 2014-05-27
  • 1970-01-01
  • 1970-01-01
  • 2017-02-21
  • 2010-12-03
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2018-03-01
相关资源
最近更新 更多