You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取展平R语言S4Vector中DFrame列表字段的GOID并生成数据框

解决方案

以下代码可直接实现需求,无需额外依赖除S4Vectors外的包:

library(S4Vectors)

# 定义提取+拼接GOID的辅助函数
process_go <- function(go_list_col) {
  vapply(go_list_col, FUN = function(item) {
    # 匹配所有以GO:开头的ID
    valid_goids <- grep(pattern = "^GO:", x = item, value = TRUE)
    # 用分号拼接,无匹配时返回空字符串
    paste(valid_goids, collapse = ";")
  }, FUN.VALUE = character(1))
}

# 构造输出数据框
result_df <- data.frame(
  query = res$query,
  go.BP = process_go(res$go.BP),
  go.CC = process_go(res$go.CC),
  go.MF = process_go(res$go.MF),
  check.names = FALSE,
  stringsAsFactors = FALSE
)

如果你习惯使用tidyverse生态工具,也可以使用以下简化写法:

library(S4Vectors)
library(dplyr)
library(purrr)
library(stringr)

result_df <- as_tibble(res) %>%
  mutate(
    across(c(go.BP, go.CC, go.MF), ~map_chr(.x, \(x) str_subset(x, "^GO:") %>% paste(collapse = ";")))
  ) %>%
  select(query, go.BP, go.CC, go.MF)

说明

  • 无匹配GOID的位置会默认返回空字符串,如需改为返回NA,可在paste前添加判断:if(length(valid_goids) == 0) NA_character_ else paste(valid_goids, collapse = ";")
  • 输出数据框每行对应原DFrame中的一个基因,三个GO列均为分号分隔的GOID字符串,符合要求。

内容的提问来源于stack exchange,提问作者ihateR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 11:06:04