簡體   English   中英

如何從2個字符串向量創建1和0矩陣?

[英]How do I create 1s and 0s matrix from 2 vectors of strings?

我正在創建一個1和0的矩陣。 如果一個單詞是字符串的一部分,則為1,否則為0。

例如,預期矩陣將如下所示:

                           white hanging heart holder black suitcase
white hanging heart holder     1       1     1      1     0        0
black suitcase                 0       0     0      0     1        1

我可以使用的是2個向量:

Itemsvector = c("white hanging heart holder","black suitcase", ...)
Wordsvector = c("white","hanging","heart","holder","black", "suitcase",...)

我正在玩%運算符中的%

strsplit(Itemsvector[1], split = ' ')[[1]] %in% Wordsvector

grepl(Wordsvector[1], Itemsvector)

這確實給了我TRUE和FALSE值,雖然我迷失了將這組值映射到整個矩陣網格。

將“Itemsvector”拆分為vector s list后,我們可以更輕松地使用table ,將其stack到data.frame並使用table

table(stack(setNames(strsplit(Itemsvector, " "), Itemsvector))[2:1])
#                             values
#ind                          black hanging heart holder suitcase white
#  white hanging heart holder     0       1     1      1        0     1
#  black suitcase                 1       0     0      0        1     0

或者使用mtabulate

library(qdapTools)
mtabulate(setNames(strsplit(Itemsvector, " "), Itemsvector))

你可以嘗試使用double sapply ,因為你已經有了Wordsvector來搜索不需要再次拆分Itemsvector 我們可以發現,如果一個特定的詞尤其存在或不Itemsvector使用grepl和額外的預防措施,我們添加單詞邊界上,所以它不匹配"white"與“ whites"

+(t(sapply(Itemsvector, function(x) sapply(Wordsvector, function(y) 
                                  grepl(paste0("\\b",y, "\\b"), x)))))

#                           white hanging heart holder black suitcase
#white hanging heart holder     1       1     1      1     0        0
#black suitcase                 0       0     0      0     1        1

數據

Itemsvector = c("white hanging heart holder","black suitcase")
Wordsvector = c("white","hanging","heart","holder","black", "suitcase")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM