How to create a binary relation matrix of pair occurrences from a list of strings?

梦想的初衷 提交于 2019-12-11 06:04:54

问题


have a list of files that contain specific genes, and I want to create a binary relation matrix in R that shows the presence of each gene in each file.

For example, here are my files aaa, bbb, ccc, and ddd and the genes associated to them.

aaa=c("HERC1")
bbb=c("MYO9A", "PKHD1L1", "PQLC2", "SLC7A2")
ccc=c("HERC1")
ddd=c("MACC1","PKHD1L1")

I need to generate another table that where, for each pair of genes, I assign the value 1 if both of them present in the specific file, and 0 other wise. Following the example that I gave earlier, this new table should look like the following one:

Does anybody know a quick way to obtain this new bigenic table in R? Thanks!


回答1:


Assuming you can read the the files into a named list, here's one way using tidyverse -

file_list <- list(aaa = aaa, bbb = bbb, ccc = ccc, ddd = ddd)

result <- stack(file_list) %>% 
  inner_join(stack(file_list), by = c("ind" = "ind")) %>% 
  select(gene1 = values.x, gene2 = values.y, file_name = ind) %>%
  mutate(n = 1) %>% 
  complete(gene1, gene2, file_name, fill = list(n = 0)) %>% 
  filter(gene1 != gene2,
         !duplicated(
           apply(., 1, function(x) paste0(sort(x), collapse = ""))
         )
  ) %>% 
  spread(file_name, n)

# A tibble: 15 x 6
   gene1   gene2     aaa   bbb   ccc   ddd
   <chr>   <chr>   <dbl> <dbl> <dbl> <dbl>
 1 HERC1   MACC1       0     0     0     0
 2 HERC1   MYO9A       0     0     0     0
 3 HERC1   PKHD1L1     0     0     0     0
 4 HERC1   PQLC2       0     0     0     0
 5 HERC1   SLC7A2      0     0     0     0
 6 MACC1   MYO9A       0     0     0     0
 7 MACC1   PKHD1L1     0     0     0     1
 8 MACC1   PQLC2       0     0     0     0
 9 MACC1   SLC7A2      0     0     0     0
10 MYO9A   PKHD1L1     0     1     0     0
11 MYO9A   PQLC2       0     1     0     0
12 MYO9A   SLC7A2      0     1     0     0
13 PKHD1L1 PQLC2       0     1     0     0
14 PKHD1L1 SLC7A2      0     1     0     0
15 PQLC2   SLC7A2      0     1     0     0 


来源:https://stackoverflow.com/questions/56193505/how-to-create-a-binary-relation-matrix-of-pair-occurrences-from-a-list-of-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!