Reputation: 1442
I have this dataframe:
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
And I have this list:
$`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"
Is there any way to print the elements of the list to a new column of the data frame? The order is the same in both structures, I mean, the GO.ID column is ordered as the list elements. I'm looking for something like paste bash command.
I've tried lapply
and export the list to a file. Then write.table
with the dataframe and then paste
command in bash. But I'm wondering if there is a way to do this kind of job in R.
And yes, I'm newbie to R world.
EDIT:
This is my desired output:
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
Upvotes: 3
Views: 5586
Reputation: 3036
(I apologise for using dplyr
here. All of this can be done using built-in R functions but I don't remember the last time I used them)
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)
And your result
would be:
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
Upvotes: 2
Reputation: 31161
If df
is your data.frame and lst
your list, you can do:
transform(df, Gene_ID=sapply(lst, paste0, collapse=',')[GO.ID])
Upvotes: 6