How to create a venn diagram from a grouped data frame based on a single column?

322 Views Asked by At

Interestingly, all the libraries and resources I have found either use lists or multiple columns. I would like to create a Venn diagram based on a grouped data frame (one column group and another column with items to be compared). What would be the easiest approach?

data.frame(groups = c(rep(1, 10), rep(2, 8)), items = c(LETTERS[1:10], LETTERS[7:14]))
1

There are 1 best solutions below

0
vqf On

You can just transform the data into what the packages are expecting. From my own experience when creating nVennR, you cannot anticipate every entry format. That is why developers tend to rely on users to convert data:

t <- data.frame(groups = c(rep(1, 10), rep(2, 8)), items = c(LETTERS[1:10], LETTERS[7:14]))

cnames <- levels(as.factor(t$groups))
r <- list()
for (c in cnames){
  r[[c]] <- as.vector(t[t[,1]==c,2])
}

Now, r has a list of vectors, which is what some packages (including nVennR) expect:

library(nVennR)

myV <- plotVenn(r)

listVennRegions(myV)

$`0, 1 (2)`
[1] "K" "L" "M" "N"

$`1, 0 (1)`
[1] "A" "B" "C" "D" "E" "F"

$`1, 1 (1, 2)`
[1] "G" "H" "I" "J"