Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
105 views
in Technique[技术] by (71.8m points)

How do I filter the table() function in R when I pass two inputs in table(A,B)

I trying to make a heatmap of a subsection of a frequency table. How do I filter the table() function in R when I pass two inputs in table(A,B).

I tried something like

tbl <-  table(A,B)
tbl[tbl>=10]

But i just get back the frequencies without the information of what it is.

question from:https://stackoverflow.com/questions/65927611/how-do-i-filter-the-table-function-in-r-when-i-pass-two-inputs-in-tablea-b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Do it this way

tbl <- as.data.frame(table(A, B))

It should gave you three columns data.frame: A, B, Freq which should be sufficient for your heatmap with code similar to this sample working example

library(stringi)
library(dplyr)
library(ggplot2)

n <- 10000
A <- stri_rand_shuffle(stri_rand_strings(n, 1, '[a-z]'))
B <- stri_rand_shuffle(stri_rand_strings(n, 1, '[a-z]'))

tbl <- as.data.frame(table(A, B)) %>%
  arrange(A, B) %>%
  filter(Freq >= 10)
ggplot(data = tbl, aes(x = A, y = B, fill = Freq)) +
  geom_tile()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...