如何删除包含NA的数据框中的行但是为某些行留下例外?

时间:2017-03-23 22:01:27

标签: r

我的df有大约17,000行(基因)和200列(患者),我需要去除含有NA的基因,但其中12个对我的分析很重要,所以不要去除它们,我要删除任何这12个基因中任何一个都有NA的患者。

我该怎么编码呢? (找不到任何类似的问题,抱歉)

1 个答案:

答案 0 :(得分:-1)

在您的问题中包含玩具示例以及您期望的结果总是好的。它可以帮助用户回答您的问题,而无需编写玩具示例。我做了一个小例子,有5名患者,5个重要基因和5个不太重要的基因。

您可以分两步完成所需的操作。首先,我们删除colSumsis.na的患者。换句话说,我们只计算重要基因行(第1行到第5行)每列NA的数量。我们只保留NA s的数量为零的列。然后我们只需na.omit来移除NA s的基因。

#Example data:
df1 <-data.frame(matrix(sample(letters,50,replace=TRUE),ncol=5))
colnames(df1) <-paste0("patient",1:5)
rownames(df1) <-c(paste0("important",1:5),paste0("lessimportant",6:10))
df1[2,4] <-NA;df1[7,1] <-NA;df1[9,5] <-NA #add NA for example

df1
                patient1 patient2 patient3 patient4 patient5
important1             m        f        d        t        m
important2             t        v        j     <NA>        d
important3             s        n        h        t        p
important4             h        h        t        n        i
important5             x        t        c        r        p
lessimportant6         y        f        b        a        h
lessimportant7      <NA>        o        h        n        a
lessimportant8         o        g        o        l        x
lessimportant9         m        p        f        d     <NA>
lessimportant10        n        a        h        u        a

#to remove NAs according to your specifications
df1 <-df1[,colSums(is.na(df1[1:5,]))==0] # remove patients with NA in important genes
df1 <-na.omit(df1) #remove genes with NA

#result
df1
                patient1 patient2 patient3 patient5
important1             m        f        d        m
important2             t        v        j        d
important3             s        n        h        p
important4             h        h        t        i
important5             x        t        c        p
lessimportant6         y        f        b        h
lessimportant8         o        g        o        x
lessimportant10        n        a        h        a
相关问题