将列表元素附加到数据框列

时间:2015-04-30 09:55:53

标签: r

我有这个数据框:

       GO.ID Annotated Significant Expected P-value                   Term Ontology
1 GO:0000049         7           0     0.25  1.0000           tRNA binding       MF
2 GO:0000062         4           0     0.14  1.0000 fatty-acyl-CoA binding       MF

我有这个清单:

$`GO:0000049`
[1] "Solyc02g090860.2" "Solyc03g119280.2" "Solyc05g056260.2" "Solyc06g048610.2" "Solyc07g008950.2" "Solyc08g015960.2"
[7] "Solyc10g007060.2"

$`GO:0000062`
[1] "Solyc01g099350.2" "Solyc03g082910.2" "Solyc04g078090.2" "Solyc08g075690.2"

有没有办法将列表元素打印到数据框的新列?两个结构中的顺序相同,我的意思是,GO.ID列按列表元素排序。我正在寻找像粘贴bash命令一样的东西。

我已尝试lapply并将列表导出到文件中。然后使用数据帧write.table,然后使用bash中的paste命令。但是我想知道是否有办法在R中做这种工作。

是的,我是R世界的新手。

修改

这是我想要的输出:

       GO.ID Annotated Significant Expected P-value                   Term Ontology           Gene_ID
1 GO:0000049         7           0     0.25  1.0000           tRNA binding       MF           Solyc02g090860.2,Solyc03g119280.2,Solyc05g056260.2,Solyc06g048610.2,Solyc07g008950.2,Solyc08g015960.2,Solyc10g007060.2
2 GO:0000062         4           0     0.14  1.0000 fatty-acyl-CoA binding       MF           Solyc01g099350.2,Solyc03g082910.2,Solyc04g078090.2,Solyc08g075690.2 

2 个答案:

答案 0 :(得分:3)

如果df是您的data.frame并且lst是您的列表,则可以执行以下操作:

transform(df, Gene_ID=sapply(lst, paste0, collapse=',')[GO.ID])

答案 1 :(得分:2)

(我在这里使用dplyr道歉。所有这一切都可以使用内置的R函数完成,但我不记得上次使用它们了吗?

library(dplyr)
library(tidyr)

# sample data
l <- list("GO.0000049" = c(1,2,3), "GO:0000062" = c(4,5,6))
df <- data.frame(GO.ID = c("GO.0000049", "GO:0000062"), Annotated = c(7,4), stringsAsFactors = F)

# actual magic
result <- gather(as_data_frame(lapply(l, function(x) paste(x, collapse=","))), "GO.ID", "Gene_ID") %>% inner_join(df)

您的result将是:

Source: local data frame [2 x 3]

       GO.ID Gene_ID Annotated
1 GO.0000049   1,2,3         7
2 GO:0000062   4,5,6         4
相关问题