【问题标题】:Read Fasta alignment file into R in order to get each nucleotide from several sequences in one column将 Fasta 比对文件读入 R,以便从一列中的多个序列中获取每个核苷酸
【发布时间】:2026-02-01 02:25:02
【问题描述】:

我想知道是否有一种方法可以将 Fasta 比对文件写入 R 以便在一列中获取每个序列的每个核苷酸? 比如:

>sample1
atgc
>sample2
aagc

我想在 R 中获得 5 列,第一列是样本名称,然后是每列来自每个样本的核苷酸。

sample1 a t g c
sample2 a a g c

这可能吗?

【问题讨论】:

    标签: r alignment fasta


    【解决方案1】:

    首先你需要读入你的文件。 readLines() 将文件转换为字符向量,每行一个元素。假设该文件仅包含您问题中显示的类型的数据,您可以使用:

    file_lines <- readLines("\your\file\path.file")
    

    然后,dplyrstringrtidyr 中的函数可以帮助您清理数据。

    library(dplyr)
    library(stringr)
    library(tidyr)
    
    matrix(file_lines, ncol = 2, byrow = TRUE) %>%
      as.data.frame() %>%
      rename(sample = V1) %>%
      mutate(sample = str_remove(sample, ">")) %>%
      separate(V2, into = paste0(".", 1:4), sep = 1:4)
    
       sample .1 .2 .3 .4
    1 sample1  a  t  g  c
    2 sample2  a  a  g  c
    

    【讨论】: