我认为最好的方法是使用以下软件包 dplyr、tidyr 和 magrittr。
首先你应该生成一个可重现的例子
library(magrittr)
library(dplyr)
library(tidyr)
#Reproducible example
Nucleo <- c("A","T","G","C")
df <- data.frame(gene=paste0("Gene",1:20))
for(x in 1:21){
df[[paste0("pos_",x)]] <- sample(Nucleo, 20, replace = T)
}
接下来我们将整理数据框以便我们可以对其进行操作。
df <- gather(df, key = "Position", value = "Nucleotide", -gene)
frequency <- df %>%
group_by(gene, Nucleotide) %>% #specify which groups we will mutate on
mutate(NucleotitdeCount=n()) %>% #For each gene and Nucleotide type - Count total
select(gene, Nucleotide, NucleotitdeCount) %>% #Specify Columns we need
distinct() %>% ungroup() %>% #reduce size to unique instances
group_by(gene) %>% #Regroup by gene to mutate over nucleotide counts
mutate(relativeFreq=NucleotitdeCount/sum(NucleotitdeCount)) #Calculate Relative Frequency
我认为最好将数据保持原样,但如果您想将其返回为长格式:
freqLong <- frequency %>%
select(gene, Nucleotide, relativeFreq) %>%
spread(key = "Nucleotide", value = "relativeFreq")
使用 ggplot2 包将其保留为以前的形式使可视化变得容易
library(ggplot2)
ggplot(frequency, aes(gene, relativeFreq, fill = Nucleotide)) +
geom_bar(stat = "identity", position = "stack")
这样做的好处是你一开始不需要担心过滤。
但是,如果您想先过滤基因,也可以使用 dplyr 函数 filter
我建议将它与grepl 结合使用以进行模式匹配。
这是我在数据集 iris 的 Species 列中匹配“seto”的示例
iris %>% filter(grepl(pattern = "seto", x = Species)) %>% head()
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 5.1 3.5 1.4 0.2 setosa
#2 4.9 3.0 1.4 0.2 setosa
#3 4.7 3.2 1.3 0.2 setosa
#4 4.6 3.1 1.5 0.2 setosa
#5 5.0 3.6 1.4 0.2 setosa
#6 5.4 3.9 1.7 0.4 setosa