【问题标题】:How to looping over a column and if pattern matches, count related characters in other columns using R?如何遍历列,如果模式匹配,使用 R 计算其他列中的相关字符?
【发布时间】:2020-01-21 19:02:34
【问题描述】:

0

我有一个 1000 行 21 列的数据框(附图),第一列是 miRNA 基因名称,其他列显示每个位置的每个核苷酸:(附图)

我想要的是在第一列上进行循环,如果我的字符模式在列中匹配,例如“Ami-Mir-489”(不考虑 p1 和 p2),那么对于每个位置(pos_1, pos_2, ..., pos_20) 分别计算每个核苷酸的频率。

enter image description here

【问题讨论】:

  • 欢迎来到 Stack Overflow。请参阅有关如何创建最小的、可重现的示例 (here) 的指南,并尝试相应地编辑您的问题。这里的关键部分是添加用于测试解决方案的数据。

标签: r loops dataframe for-loop


【解决方案1】:

我认为最好的方法是使用以下软件包 dplyrtidyrmagrittr

首先你应该生成一个可重现的例子

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

【讨论】:

  • 贾斯汀感谢您的回答。我尝试运行您建议的命令行,但频率脚本出现此错误:错误:n() 只能在数据上下文中调用调用rlang::last_error() 以查看回溯
  • 另一个问题,因为我无法运行频率脚本,我用过滤设置了我的 df,根据我的模式,我有 300 个具有相同模式的基因(这些是不同物种的 miRNA 家族)。话虽如此,对于我的模式中的 300 个基因总数,我想获得每个位置中每个核苷酸的百分比。这是频率脚本的作用吗?
  • @mortezaaslanzadeh ,通常只在这些 dplyr 语句中调用 n() 函数,但它在功能上与计算向量的长度相同,如果将 n() 替换为 length(Nucleotide) this代码应该仍然运行相同。确保你从 cran 获得 dplyr tidyrmagrittr
猜你喜欢
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2012-09-26
  • 2018-07-15
相关资源
最近更新 更多