简体   繁体   English

如果r中的行低于同一列的最后一行的值,则将其删除

[英]delete the rows in r if it is below the value of the last row at the same column

I am beginner in r, and trying to delete all rows, which contain values that are less than the "control" or last row, in each column. 我是r的初学者,并尝试删除所有列中的所有行,这些行包含的值小于“控件”或最后一行的值。 For this sample data: 对于此样本数据:

        A   B   C   D    E
gene1   14  6   8   16  14
gene2   5   6   10  6   4
gene3   2   4   6   3   4
gene4   26  6   18  39  36
gene5   1   2   3   1   2
gene6   2   1   3   1   1
control 8   5   5   4   11

I would like to remove all rows that are less than control (including control) leading to: 我想删除所有小于控件(包括控件)的行,导致:

gene1   14  6   8   16  14
gene4   26  6   18  39  36

Thank you in advance!! 先感谢您!! (sorry, I do not know how to post the question. Hope you could understand what I mean.) (对不起,我不知道如何发布问题。希望您能理解我的意思。)

THere's no way to delete anything from data.frame . 无法从data.frame删除任何data.frame You can only subset a data.frame . 您只能子集一个data.frame You may then assign this subset to any variable. 然后,您可以将此子集分配给任何变量。 First initialize your data.frame: 首先初始化您的data.frame:

df <- read.table(text = "
        A   B   C   D    E
gene1   14  6   8   16  14
gene2   5   6   10  6   4
gene3   2   4   6   3   4
gene4   26  6   18  39  36
gene5   1   2   3   1   2
gene6   2   1   3   1   1
control 8   5   5   4   11
", header = TRUE)

Now, the operation is much easier done on a matrix, and transposed. 现在,该操作在矩阵上进行转换要容易得多。 Then it is as straightforward as it can be: 然后,它就尽可能简单明了:

m <- t(as.matrix(df))
df[apply(m > m[,'control'], 2, all),]

#       A B  C  D  E
# gene1 14 6  8 16 14
# gene4 26 6 18 39 36

So first you compare all the matrix elements ( m > m[,'control'] ) and then you perform all (logical AND) operation by rows (sensu df , actually it is by columns of the transposed matrix). 因此,首先比较所有矩阵元素( m > m[,'control'] ),然后按行执行all (逻辑AND)操作(sensu df ,实际上是按转置矩阵的列进行)。 And finally you subset the df . 最后,您将df子集化。

Here is solution. 这是解决方案。

coolFun<-function(dat,control_vec){ #alternatively you can remove control_vec from here
    aux<-c()
    for(i in 1:nrow(dat)) # iterate to nrow(dat)-1 only
        if(all(dat[i,]>control_vec)==TRUE) #and change it with dat[nrow(dat),]
            aux<-rbind(aux,dat[i,])
    }
    aux
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM