【问题标题】:How do I remove rows in a data frame that contain NAs but leave exceptions for certain rows?如何删除数据框中包含 NA 但为某些行留下异常的行?
【发布时间】:2017-08-16 16:50:44
【问题描述】:

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

我将如何编写代码? (找不到类似的问题,抱歉)

【问题讨论】:

  • na.omit 函数可能很有用。
  • 对 - 但我如何将它应用于 17,000 行,但 12 个特定行除外?
  • 也许为 12 名患者创建一个子集作为新数据框。没有 12 名患者的第二个子集。将 na.omit 应用于第二个数据帧以生成第三个数据帧。之后,使用 cbind 合并第一个和第三个数据框。
  • 因为您没有提供示例数据集,其他人很难提供解决方案。

标签: r


【解决方案1】:

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

你可以分两步做你想做的事。首先,我们删除带有colSumsis.na 的患者。换句话说,我们只计算重要基因行(行 1:5)每列有多少 NAs。我们只保留NAs 的数量为零的列。然后我们只需使用na.omit 来删除带有NAs 的基因。

#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

【讨论】:

    猜你喜欢
    • 2012-10-12
    • 2013-08-09
    • 2014-04-03
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多