首页 > 解决方案 > 找到所有具有共同索引的数字 - R

问题描述

我有两个数字,这样

beta: 
  chr4       chr4       chr5       chr7       chr7       chr7 
0.01960784 0.01960784 0.01960784 0.00000000 0.00990099 0.01941748 

coefficients:
  chr1    chr4    chr4    chr7    chr7    chr8 
 0.7605  0.1261  4.3766  5.6856 -0.5194 -0.6355 

我想找到所有共同染色体的数量,例如

beta:
chr4       chr4          chr7       chr7       chr7 
0.01960784 0.01960784 0.01941748 0.01960784 0.01960784

coefficients:
chr4    chr4    chr7    chr7   
0.1261  4.3766  5.6856 -0.5194 

到目前为止我做了什么:

x = beta
f <- mouse$coefficients

common_sites_index <- intersect(names(x), names(f))

reduced_beta <- x[common_sites_index]
reduced_model <- f[common_sites_index]

但是我只是得到第一个结果

chr4         chr7       
0.01960784  0.01941748

chr4       chr7    
0.1261    5.6856

标签: r

解决方案


[将只返回第一场比赛。用于%in%比较名称和子集值。

reduced_beta <- x[names(x) %in% common_sites_index]
reduced_model <- f[names(f) %in% common_sites_index]

您可以在这个小示例中看到不同之处:

x <- c(a = 2, b = 3, a = 4)
x['a']
#a 
#2 
x[names(x) %in% 'a']
#a a 
#2 4 

推荐阅读