user3130644
user3130644

Reputation: 101

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. 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.)

Upvotes: 2

Views: 738

Answers (2)

Tomas
Tomas

Reputation: 59465

THere's no way to delete anything from data.frame. You can only subset a data.frame. You may then assign this subset to any variable. First initialize your 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). And finally you subset the df.

Upvotes: 3

user974514
user974514

Reputation: 552

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
}

Upvotes: 1

Related Questions