R:获取每列间隔内的范围和频率?

时间:2020-07-11 20:14:08

标签: r lapply sapply

我有大约300行,每个代表一个基因,大约30个类别作为列。我的数据集看起来像这样:

   Gene   bile_duct
1 ABCA2 -0.01319722
2 ABCA3 -0.06648552
3 ABCA5 -0.05049298

我正在尝试1)计算每一列在[-3,-1]某个范围内的基因频率 和2)列出上述范围内的基因的实际清单。

我不确定如何处理(2)。对于(1),我的方法行不通,但是它尝试先剪切数据,然后将lapply与range函数一起使用:

breaks = seq(-3,-1, by=2)
cut_lineage <- lapply(lineage_genes[,-1],cut,breaks)
cut_lineage <- lapply(cut_lineage,range)

3 个答案:

答案 0 :(得分:0)

我们可以使用base R。如果要在单个窗口中获取值的范围,请使用><子集数据,并在其上应用range

lapply(lineage_genes[,-1], function(x) range(x[x >= -3 & x <=-1]))

如果我们需要“ Gene”列表,而不是子集值,则将“ Gene”子集

lapply(lineage_genes[,-1], function(x) lineage_genes$Gene[x >= 3 & x <= -1])

在OP的代码中,我们将返回cut而不是实际列值的组,它是factor类型。因此,range将应用于剪切组而不是值的子集

答案 1 :(得分:0)

您可以在base R中尝试此解决方案:

#Data

Data2 <- structure(list(Gene = structure(1:3, .Label = c("ABCA2", "ABCA3", 
"ABCA5"), class = "factor"), bile_duct = c(-0.01319722, -0.06648552, 
-0.05049298), bile_duct2 = c(-0.01319722, -0.06648552, -0.05049298
)), class = "data.frame", row.names = c(NA, -3L))

#Function
cuts <- function(x,a,b)
{
  y<-ifelse(x>=a & x<=b,1,0)
  return(y)
}

cuts(-1.5,a = -3,b = -1)
#Apply function and create a copy of data
Data3 <- Data2
Data3[,-1] <- apply(Data2[,-1],2,cuts,a = -3,b = -1)

#Obtain sums for all columns
Sum <- colSums(Data3[,-1])
#Summary by gene
aggregate(.~Gene,data=Data3,FUN = sum,na.rm=T)

Sum
bile_duct bile_duct2 
         0          0 

聚合应该随着更多的数据显示值的数量而改变:

   Gene bile_duct bile_duct2
1 ABCA2         0          0
2 ABCA3         0          0
3 ABCA5         0          0

我希望这会有所帮助。

答案 2 :(得分:0)

以下几行将在数据框中存储所需的频率。

freqs = data.frame(col = '', n = NA)
for (i in 2:ncol(data)) {
    freqs = rbind(freqs, 
                data.frame(
                        col = names(data[i]), 
                        n = nrow(data[which(data[,i] >= -3 & data[,i] <= -1), ])
                    )
                )
}
freqs = freqs[-1,]

以下几行将实际的基因存储在列表对象中。列表对象中的每个项目都属于其中一列。

lists = vector('list', ncol(data)-1)

for (i in 2:ncol(data)) {

    lists[[i]] = data[which(data[,i] >= -3 & data[,i] <= -1), 1]

}

如果您用于每列的条件都不同,则这些条件将不起作用。