I have two different tables that I got using the table()
command (on a matrix). The first table has around 200 words and their frequencies of appearance, and the second table has around 400 words and their frequencies of appearance. I want to know how many times each word appeared in the 1st table and the 2nd table (not the total amount of appearances).
Asked
Active
Viewed 72 times
0
-
Try `merge(table1, table2, by = "word", all = T)`. – Psidom Jun 09 '16 at 23:36
-
2http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Hack-R Jun 09 '16 at 23:43
1 Answers
1
x <- c("a", "the", "cat", "dog", "money", "dog", "money", "dog", "money")
y <- c("a", "the", "cat", "cat", "cat", "dog", "money", "dog", "money", "women")
xx <- table(x)
yy <- table(y)
xx <- data.frame(xx) # Get it out of the table class
colnames(xx) <- c("word", "table1_freq") # name columns appropriately
yy <- data.frame(yy) # Get it out of the table class
colnames(yy) <- c("word", "table2_freq") # name columns appropriately
pacman::p_load(rowr)
result <- cbind.fill(xx,yy, fill=NA)
# Now to replace the NA's with what you requested in the comment:
result$table1_freq <- as.numeric(result$table1_freq)
result$table2_freq <- as.numeric(result$table2_freq)
result$table1_freq[is.na(result$table1_freq)] <- 0
result$table2_freq[is.na(result$table2_freq)] <- 0
result[,1] <- as.character(result[,1])
result[,3] <- as.character(result[,3])
result[is.na(result[,1]),1] <- result[is.na(result[,1]),3]
result[is.na(result[,3]),3] <- result[is.na(result[,3]),1]
result
word table1_freq word table2_freq
1 a 1 a 1
2 cat 1 cat 3
3 dog 2 dog 2
4 money 2 money 2
5 the 1 the 1
6 women 0 women 1
>
I used pacman
here, but you could also just install the package normally if you don't have it and use require
or library

Hack-R
- 22,422
- 14
- 75
- 131
-
Now suppose that x also had an occurence of the word "bat." I want the words to be aligned when they appear in the table below, so if bat doesn't appear in table 2, it's frequency should show up to 0. How do I do this? – Green Jun 10 '16 at 18:24
-
@A.Manimaran OK it's updated now (the word "women" is only in Table 2). Please feel free to upvote and select this as the solution if it was helpful. :) – Hack-R Jun 10 '16 at 19:49