我有一个非常大的csv文件(大约9100万行,因此for循环在R中需要太长时间)关键字之间的相似性,当我读入data.frame看起来像:
> df
kwd1 kwd2 similarity
a b 1
b a 1
c a 2
a c 2
这是一个稀疏列表,我想将其转换为稀疏矩阵:
> myMatrix
a b c
a . 1 2
b 1 . .
c 2 . .
我尝试使用sparseMatrix(),但将关键字名称转换为整数索引需要花费太多时间。
感谢您的帮助!
答案 0 :(得分:1)
acast
包的 reshape2
可以很好地完成此操作。有基本R解决方案,但我觉得语法更难。
library(reshape2)
df <- structure(list(kwd1 = structure(c(1L, 2L, 3L, 1L), .Label = c("a",
"b", "c"), class = "factor"), kwd2 = structure(c(2L, 1L, 1L,
3L), .Label = c("a", "b", "c"), class = "factor"), similarity = c(1L,
1L, 2L, 2L)), .Names = c("kwd1", "kwd2", "similarity"), class = "data.frame", row.names = c(NA,
-4L))
acast(df, kwd1 ~ kwd2, value.var='similarity', fill=0)
a b c
a 0 1 2
b 1 0 0
c 2 0 0
>
使用sparseMatrix
包中的Matrix
:
library(Matrix)
df$kwd1 <- factor(df$kwd1)
df$kwd2 <- factor(df$kwd2)
foo <- sparseMatrix(as.integer(df$kwd1), as.integer(df$kwd2), x=df$similarity)
> foo
3 x 3 sparse Matrix of class "dgCMatrix"
foo <- sparseMatrix(as.integer(df$kwd1), as.integer(df$kwd2), x=df$similarity, dimnames=list(levels(df$kwd1), levels(df$kwd2)))
> foo
3 x 3 sparse Matrix of class "dgCMatrix"
a b c
a . 1 2
b 1 . .
c 2 . .