我有一个大型数据集,其中包含一列基因名称和四列检测方法(在本例中,我将它们称为X1、X2、X3和X4)。我想选择至少通过两种检测方法选择基因的行。该表的示例如下:
Table:
Row Gene X1 X2 X3 X4
1 A 1 0 0 0
2 A 0 0 1 0
3 A 0 1 0 0
4 B 0 0 1 0
5 B 0 0 1 0
6 C 0 0 0 1
7 D 0 0 1 0
8 D 0 1 0 0
9 D 0 1 0 0
10 E 0 0 1 0
11 E 0 0 1 0总之,我想选择行1,2,3 (方法X1,X2和X3检测到基因A)和行7,8,9,其中方法X2和X3检测到基因D。
谢谢你的帮助。
发布于 2020-12-01 19:04:20
为了显示哪些基因是通过两种或两种以上的方法检测出来的,这是可行的。
简短版本:
如果zz是您的data.frame,则:
yy <- by(zz, zz$Gene, function(dat) {sum(apply(dat[,-c(1,2)], 2, any)) >= 2} )
zz[zz$Gene %in% which(yy),]长版本
# load the data:
zz <- read.table(header = TRUE, text = "
Row Gene X1 X2 X3 X4
1 A 1 0 0 0
2 A 0 0 1 0
3 A 0 1 0 0
4 B 0 0 1 0
5 B 0 0 1 0
6 C 0 0 0 1
7 D 0 0 1 0
8 D 0 1 0 0
9 D 0 1 0 0
10 E 0 0 1 0
11 E 0 0 1 0")
# now check, gene by gene, whether at least two columns have at least one 1.
# note that the repeated any() statements can be replaced by a loop or
# apply(), but for only four columns this works, is easy enough to type,
# and much easier to understand
yy <- by(zz, zz$Gene, function(dat) {(any(dat$X1) +
any(dat$X2) +
any(dat$X3) +
any(dat$X4) ) >= 2} )
# or, the apply way, in case there are a lot of columns.
# "-c(1,2)" as a column index means "every column except the first two",
# so if the data has 3, 4, or 30 methods, this code stays the same.
yy <- by(zz, zz$Gene, function(dat) {sum(apply(dat[,-c(1,2)], 2, any)) >= 2} )
yy
zz$Gene: A
[1] TRUE
---------------------------------------------------------------------------
zz$Gene: B
[1] FALSE
---------------------------------------------------------------------------
zz$Gene: C
[1] FALSE
---------------------------------------------------------------------------
zz$Gene: D
[1] TRUE
---------------------------------------------------------------------------
zz$Gene: E
[1] FALSE现在找到与获得TRUE结果的基因相匹配的行。
查找zz (A、B、C、... )的名称与TRUE的yy值相对应,并基于此对data.frame进行索引...
which(yy) # equivalent to which(yy == TRUE)给出
A D
1 4 和
names(which(yy))给出
[1] "A" "D"所以..。
zz[zz$Gene %in% names(which(yy)),]给出
Row Gene X1 X2 X3 X4
1 1 A 1 0 0 0
2 2 A 0 0 1 0
3 3 A 0 1 0 0
7 7 D 0 0 1 0
8 8 D 0 1 0 0
9 9 D 0 1 0 0发布于 2020-12-01 19:18:55
您可以使用rowsum和rowSums查找具有多个方法的行,使用%in%查找匹配的行。
x <- rowSums(rowsum(zz[3:6], zz[,2]) > 0) > 1
zz$Row[zz$Gene %in% names(x[x])]
#[1] 1 2 3 7 8 9https://stackoverflow.com/questions/65089039
复制相似问题