(apologies, I wasn't sure what the best title for this post would be, feel free to edit).
Lets say I have the following relational structure between words and their type (i.e. a dictionary):
dictionary <- data.frame(level1=c(rep("Positive", 3), rep("Negative", 3)), level2 = c("happy", "fantastic", "great", "sad", "rubbish", "awful"))
# level1 level2
# 1 Positive happy
# 2 Positive fantastic
# 3 Positive great
# 4 Negative sad
# 5 Negative rubbish
# 6 Negative awful
and we have counted their occurrences across seven documents (i.e. a term-document matrix):
set.seed(42)
range = 0:3
df <- data.frame(row.names = c("happy", "fantastic", "great", "sad", "rubbish", "awful"), doc1 = sample(x=range, size=6, replace=TRUE), doc2 = sample(x=range, size=6, replace=TRUE), doc3 = sample(x=range, size=6, replace=TRUE), doc4 = sample(x=range, size=6, replace=TRUE), doc5 = sample(x=range, size=6, replace=TRUE), doc6 = sample(x=range, size=6, replace=TRUE), doc7 = sample(x=range, size=6, replace=TRUE))
# doc1 doc2 doc3 doc4 doc5 doc6 doc7
# happy 3 2 3 1 0 2 0
# fantastic 3 0 1 2 2 3 0
# great 1 2 1 3 1 1 3
# sad 3 2 3 0 3 2 2
# rubbish 2 1 3 3 1 0 1
# awful 2 2 0 3 3 3 1
Then I can easily calculate how often two words appear in the same document (i.e. a co-occurrence or adjacency matrix):
# binary to indicate a co-occurrence
df[df > 0] <- 1
# sum co-occurrences
m <- as.matrix(df) %*% t(as.matrix(df))
# happy fantastic great sad rubbish awful
# happy 5 4 5 4 4 4
# fantastic 4 5 5 4 4 4
# great 5 5 7 6 6 6
# sad 4 4 6 6 5 5
# rubbish 4 4 6 5 6 5
# awful 4 4 6 5 5 6
Question: How can I restructure my co-occurrence matrix so that I am looking at the word type (level1) in the dictionary rather that just the words themselves (level2)?
i.e. I would like:
data.frame(row.names = c("Positive", "Negative"), Positive = c(5+4+5+4+5+5+5+5+7, 4+4+6+4+4+6+4+4+6), Negative = c(4+4+4+4+4+4+6+6+6, 6+5+5+5+6+5+5+5+6))
# Positive Negative
# Positive 45 42
# Negative 42 48
What I've done thus far: Previously I had hoped to be able to deduce the process from this question Sum together columns of data.frame based on name type
However whilst I can reduce the rows:
require(data.table)
dt <- data.table(m)
dt[, level1:=c(rep("Positive", 3), rep("Negative", 3))]
dt[, lapply(.SD, sum), by = "level1"]
# level1 happy fantastic great sad rubbish awful
# 1: Positive 14 14 17 14 14 14
# 2: Negative 12 12 18 16 16 16
I can't work out how to reduce the columns as require.