R代码将两列(其中一列有多个需要解析的文本字符串)提取到一个命名的字符向量列表中



我目前遇到的情况是,我有一个数据帧,需要将其中两列转换为指定的格式。每列数据示例:

第1列:Some_text_String

第2列:

GO:0048046^cellular_component^apoplast`GO:0005618^cellular_component^cell wall`GO:0005576^cellular_component^extracellular region`GO:0099503^cellular_component^secretory vesicle`GO:0004252^molecular_function^serine-type endopeptidase activity`GO:0080001^biological_process^mucilage extrusion from seed coat`GO:0048359^biological_process^mucilage metabolic process involved in seed coat development`GO:0010214^biological_process^seed coat development   

所以我有两个问题。我需要解析第二列,以便只包含GO:XXXXXXXX文本。得到第一个项的部分解是stringr::str_extract(mydataframe[1,2], ".{0,8}GO.{0,8}"),但它只捕获第一个项。

其次,最终输出需要是一个命名的字符向量列表,列表名称是第一列,列表中的每个元素都是一个字符向量。这直接来自于我尝试使用的R包(topGO(的小插曲。

readMappings返回的对象是一个命名的字符列表矢量。列表名称提供了基因标识符。的每个元素该列表是一个字符向量,包含GO标识符注释到特定基因

我知道这很简单,但我只是在尝试使用apply或其他解决方案时陷入了困境,我的大脑受到了打击。

排斥:

myvector1 <- c("Some_text_String")
myvector2 <- c("GO:0048046^cellular_component^apoplast`GO:0005618^cellular_component^cell wall`")
mydataframe <-  data.frame(myvector1,myvector2)
# parse myvector2 to remove everything except GO terms.
# This code only gets the first term, but I need all of them as a vector
stringr::str_extract(mydataframe [1,2], ".{0,8}GO.{0,8}")
# At this point the desired result is named list of character vectors, with the list names being the first column and each element of the list being a character vector.

您可以使用str_extract_all提取所有满足模式的值,并使用setNames获得命名列表。

library(stringr)
setNames(str_extract_all(mydataframe [1,2], "GO.{0,8}"), mydataframe$myvector1)
#$Some_text_String
#[1] "GO:0048046" "GO:0005618"

最新更新