有没有办法循环遍历 R 中的矩阵/df 来创建邻接矩阵?



我正在尝试遍历 data.frame 中的 53 行,并使用结果创建一个邻接矩阵。但是,由于循环无法正常运行,我的努力继续停滞不前。

我尝试创建匹配项并应用许多count()函数,但没有成功。

MRE:(事实上,数据要大得多,所以我的独特搜索实际上是217k元素)

df1<-data.frame(col1=c(12345,123456,1234567,12345678),
col2=c(54321,54432,12345,76543),
col3=c(11234,12234,1234567,123345),
col4=c(54321,54432,12345,76543))
search<-c(12345,1234567,75643,54432)

我想遍历每一行并更新一个新的矩阵/df,其中 [搜索] 中每个数字的计数将是输出。

前任:

DF2

12345     1234567    75643    54432
row1    TRUE       TRUE      FALSE    FALSE
row2    FALSE      FALSE     TRUE      TRUE
row3    TRUE       TRUE      FALSE    FALSE
row4    TRUE       FALSE     TRUE     TRUE

虽然目前还不清楚您的计数是如何得出的,因为甚至可能存在拼写错误(75643 != 76543),或者您是否按行或列运行,请考虑嵌套sapply并为两个边距apply解决方案:

按行

search <- c(12345, 1234567, 76543, 54432)                                # ADJUSTED TYPO    
mat <- sapply(search, function(s) apply(df1, 1, function(x) s %in% x))   # 1 FOR ROW MARGIN
colnames(mat) <- search
rownames(mat) <- paste0("row", seq(nrow(df1)))
mat
#      12345 1234567 76543 54432
# row1  TRUE   FALSE FALSE FALSE
# row2 FALSE   FALSE FALSE  TRUE
# row3  TRUE    TRUE FALSE FALSE
# row4 FALSE   FALSE  TRUE FALSE

按列

search <- c(12345, 1234567, 76543, 54432)                                # ADJUSTED TYPO
mat <- sapply(search, function(s) apply(df1, 2, function(x) s %in% x))   # 2 FOR COL MARGIN
colnames(mat) <- search
rownames(mat) <- paste0("col", seq(ncol(df1)))
mat
#      12345 1234567 76543 54432
# col1  TRUE    TRUE FALSE FALSE
# col2  TRUE   FALSE  TRUE  TRUE
# col3 FALSE    TRUE FALSE FALSE
# col4  TRUE   FALSE  TRUE  TRUE

Rextester 演示

我认为您应该检查文本挖掘的tf (term frequency) algorithm。对于您的示例,这里有一个有趣的方法,使用library(quanteda)创建带有计数的矩阵。然后,您可以根据计数进行您喜欢的搜索:

library("tibble")
library("quanteda")

df1<-data.frame(col1=c(12345,123456,1234567,12345678),
col2=c(54321,54432,12345,76543),
col3=c(11234,12234,1234567,123345),
col4=c(54321,54432,12345,76543))
df2<-apply(df1,2,paste, collapse = " ") # Passing it to string format
DocTerm <- quanteda::dfm(df2)
DocTerm
Document-feature matrix of: 4 documents, 10 features (60.0% sparse).
4 x 10 sparse Matrix of class "dfm"
features
docs   12345 123456 1234567 12345678 54321 54432 76543 11234 12234 123345
col1     1      1       1        1     0     0     0     0     0      0
col2     1      0       0        0     1     1     1     0     0      0
col3     0      0       1        0     0     0     0     1     1      1
col4     1      0       0        0     1     1     1     0     0      0

我希望这有帮助!

最新更新