acast
from 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 . .
爲什麼你對你的問題*可能重複*頭? –
這是來自不同的帖子,對不起。 – rfoley