是否有 R 技术可以 group_by、搜索和匹配长数据结构?
Is there an R technique to group_by, search, and match a long data structure?
这是一个从每个 id
.
的 5 个单词列表中找出哪些 id
具有匹配的 word
的问题
我们有一个来自文本挖掘项目的长数据结构,带有 id
和 word
。每个 group_id 有 5 个单词。我们想测量一个 id 中的哪些 word
s 在另一个 id
中。即,根据那里的单词,哪些 ID 是相似的。
我们尝试在 [行,列] 上使用 for 循环,但似乎有更好的方法。
library(tidyverse)
data <- tibble(id = factor(c(1234, 1234, 1234, 1234, 1234,
4523, 4523, 4523, 4523, 4523,
0984, 0984, 0984, 0984, 0984)),
word = c("hello", "today", "the", "monkey", "boy",
"go", "me", "key", "wind", "hello",
"monkey", "yes", "no", "wild", "quit"))
output <- matrix(1, length(data$id), length(data$id))
for (j in 1 : length(data$id)) {
for (i in 1 : length(data$id)) {
output[i,j] <- data[i,2] == data[j,2]
}
}
output
## from the output we see that 4 and 11 match.
data[4,]
data[11,]
我的最终目标是得到一个矩阵,其中 id
乘以 id
,交点是匹配词的数量 (0-5)。
这是期望的输出:
# 1234 4523 0984
# 1234 5 1 1
# 4523 1 5 0
# 0984 1 0 5
欢迎任何关于完全重组数据结构的建议或具有此结构的解决方案。谢谢!
我们可以 split
word
通过 id
然后使用 outer
和自定义函数来计算单词在不同 id
之间出现的次数s.
count_value <- function(x, y) {
colSums(mapply(`%in%`, x, y))
}
outer(split(data$word, data$id),split(data$word, data$id), count_value)
# 984 1234 4523
#984 5 1 0
#1234 1 5 1
#4523 0 1 5
我们可以用 tcrossprod
从 base R
轻松解决
tcrossprod(table(data))
# id
#id 984 1234 4523
# 984 5 1 0
# 1234 1 5 1
# 4523 0 1 5
或与tidyverse
相同的方法
library(tidyverse)
count(data, id, word) %>%
spread(word, n, fill = 0) %>%
column_to_rownames('id') %>%
as.matrix %>%
tcrossprod
# 984 1234 4523
#984 5 1 0
#1234 1 5 1
#4523 0 1 5
这是一个从每个 id
.
id
具有匹配的 word
的问题
我们有一个来自文本挖掘项目的长数据结构,带有 id
和 word
。每个 group_id 有 5 个单词。我们想测量一个 id 中的哪些 word
s 在另一个 id
中。即,根据那里的单词,哪些 ID 是相似的。
我们尝试在 [行,列] 上使用 for 循环,但似乎有更好的方法。
library(tidyverse)
data <- tibble(id = factor(c(1234, 1234, 1234, 1234, 1234,
4523, 4523, 4523, 4523, 4523,
0984, 0984, 0984, 0984, 0984)),
word = c("hello", "today", "the", "monkey", "boy",
"go", "me", "key", "wind", "hello",
"monkey", "yes", "no", "wild", "quit"))
output <- matrix(1, length(data$id), length(data$id))
for (j in 1 : length(data$id)) {
for (i in 1 : length(data$id)) {
output[i,j] <- data[i,2] == data[j,2]
}
}
output
## from the output we see that 4 and 11 match.
data[4,]
data[11,]
我的最终目标是得到一个矩阵,其中 id
乘以 id
,交点是匹配词的数量 (0-5)。
这是期望的输出:
# 1234 4523 0984
# 1234 5 1 1
# 4523 1 5 0
# 0984 1 0 5
欢迎任何关于完全重组数据结构的建议或具有此结构的解决方案。谢谢!
我们可以 split
word
通过 id
然后使用 outer
和自定义函数来计算单词在不同 id
之间出现的次数s.
count_value <- function(x, y) {
colSums(mapply(`%in%`, x, y))
}
outer(split(data$word, data$id),split(data$word, data$id), count_value)
# 984 1234 4523
#984 5 1 0
#1234 1 5 1
#4523 0 1 5
我们可以用 tcrossprod
从 base R
tcrossprod(table(data))
# id
#id 984 1234 4523
# 984 5 1 0
# 1234 1 5 1
# 4523 0 1 5
或与tidyverse
library(tidyverse)
count(data, id, word) %>%
spread(word, n, fill = 0) %>%
column_to_rownames('id') %>%
as.matrix %>%
tcrossprod
# 984 1234 4523
#984 5 1 0
#1234 1 5 1
#4523 0 1 5