wgcna转录组数据分析

将WGCNA的检查数据集中是否有方差为0的基因写成函数

2020-02-14  本文已影响0人  淡水鱼Ada

最近在用WGCNA进行网络分析。在一个脚本中会多次检查数据集中是否会含有方差为0的基因。因此会多次修改代码,有时候可能稍微疏忽一点,就会出错。对于这种情况最好的解决办法是写成函数。

原始代码如下:

gsg_AD_lung = goodSamplesGenes(datExpr_AD_lung, verbose = 3);
gsg_AD_lung$allOK
gsg <- gsg_AD_lung #???
if (!gsg$allOK){
        # Optionally, print the gene and sample names that were removed:
        if (sum(!gsg$goodGenes)>0)
                printFlush(paste("Removing genes:", paste(names(datExpr0)[!gsg$goodGenes], collapse = ", ")));
        if (sum(!gsg$goodSamples)>0)
                printFlush(paste("Removing samples:", paste(rownames(datExpr0)[!gsg$goodSamples], collapse = ", ")));
        # Remove the offending genes and samples from the data:
        datExpr0 = datExpr0[gsg$goodSamples, gsg$goodGenes]
}

第一行代码是使用WGCNA包中的函数,计算数据集中是否含有方差为0的基因,数据集的行是样品,列是基因名字。第二行代码是检查数据集中检查数据集中是否含有方差为0的基因。返回TRUE则说明待分析的数据集中没有方差为0的基因。否则则有,需要使用第四行的代码删除数据集中的方差为0的基因,并返回删除的基因名字。

注意到第一行第二行和第四行的gsg变量名是不一致的,并且数据集的名字是不一致的。这种情况下,偷懒的方法是使用第三行,将gsg_AD_lung赋值给gsg,然后再将数据集进行赋值(这里没写)。

解决上述问题最好的办法是将第1行,第2行,第4行代码写成函数的形式。不容易出错。

顺便提一下,在R数据科学这本书中有介绍这一思想。

1编写函数

Check_data <- function(datExpr0){
        gsg = goodSamplesGenes(datExpr0, verbose = 3);
        print(gsg$allOK)
        if (!gsg$allOK){
                # Optionally, print the gene and sample names that were removed:
                if (sum(!gsg$goodGenes)>0)
                        printFlush(paste("Removing genes:", paste(names(datExpr0)[!gsg$goodGenes], collapse = ", ")));
                if (sum(!gsg$goodSamples)>0)
                        printFlush(paste("Removing samples:", paste(rownames(datExpr0)[!gsg$goodSamples], collapse = ", ")));
                # Remove the offending genes and samples from the data:
                datExpr0 = datExpr0[gsg$goodSamples, gsg$goodGenes]
        }
}

2使用

check_data(datExpr_AD_lung)
result <- check_data(datExpr_AD_lung)

第一行返回数据是否含有方差为0的基因,如果含有方差为0的基因,那么会删除哪些基因。
第二行,result是一个数据框,里面包含删除方差为0基因后的数据集。【如果数据集中含有方差为0的基因,则需要添加第二行代码,因为待分析的数据集此时已经变成删除这些基因后的数据集,也就是result这个对象。】

上一篇 下一篇

猜你喜欢

热点阅读