R:OTU根据分类级别拆分

输入文件
输出文件

rm(list = ls())
setwd("C:\\Users\\Administrator\\Desktop\\microtable") #设置工作目录
library(dplyr)
library(tidyr)
library(readr)

# 读取文件
data <- readLines('1.txt')

# 定义分类等级的前缀和列名
prefixes <- c("k__", "p__", "c__", "o__", "f__", "g__", "s__")
levels <- c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species")

# 拆分并填充缺失的分类
split_data <- lapply(data, function(line) {
  # 初始化分类向量
  classification <- setNames(rep("unclassified", length(levels)), levels)
  
  # 遍历每个前缀
  for(i in seq_along(prefixes)) {
    prefix <- prefixes[i]
    pattern <- paste0(prefix, "([^|]+)")
    matches <- regmatches(line, gregexpr(pattern, line))
    
    # 如果找到匹配项,则更新分类
    if(length(matches[[1]]) > 0) {
      name <- gsub(prefix, "", matches[[1]])
      classification[levels[i]] <- name
    }
  }
  
  return(c(line, classification))
})

# 将结果转换为数据框
result_df <- do.call(rbind, split_data)

# 添加列名
colnames(result_df) <- c("Original_Classification", levels)

# 转换为字符矩阵以便输出
result_matrix <- apply(result_df, 2, as.character)

# 输出到txt文件,包括列名
write.table(result_matrix, 'path_to_output_file.txt', quote = FALSE, sep = "\t", row.names = FALSE, col.names = TRUE)


posted @   王哲MGG_AI  阅读(47)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
历史上的今天:
2023-05-06 rgi main --input_sequence temp/out_pro.fa --output_file result/protein --input_type protein --clean --num_threads 10 --alignment_tool DIAMOND --include_loose
点击右上角即可分享
微信分享提示