user2886545
user2886545

Reputation: 713

Store list into a file (R)

I have the following data frame:

    Group.1         V2
1   27562761    GO:0003676
2   27562765    c("GO:0004345", "GO:0050661", "GO:0006006", "GO:0055114")
3   27562775    GO:0016020
4   27562776    c("GO:0005525", "GO:0007264", "GO:0005622")

where the second column is a list. I tried to write the data frame into a text file using write.table, but it did not work. My desired output is the following one (file.txt):

27562761    GO:0003676
27562765    GO:0004345, GO:0050661, GO:0006006, GO:0055114
27562775    GO:0016020
27562776    GO:0005525, GO:0007264, GO:0005622

How could I obtain that?

Upvotes: 0

Views: 46

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193507

You could look into sink, or you could use write.csv after flattening "V2" to a character string.

Try the following examples:

## recreating some data that is similar to your example
df <- data.frame(a = c(1, 1, 2, 2, 3), b = letters[1:5])
x <- aggregate(list(V2 = df$b), list(df$a), c)
x
#   Group.1   V2
# 1       1 1, 2
# 2       2 3, 4
# 3       3    5

## V2 is a list, as you describe in your question
str(x)
# 'data.frame':  3 obs. of  2 variables:
#  $ Group.1: num  1 2 3
#  $ V2     :List of 3
#   ..$ 1: int  1 2
#   ..$ 3: int  3 4
#   ..$ 5: int 5

sink(file = "somefile.txt")
x
sink()
## now open up "somefile.txt" from your working directory


x$V2 <- sapply(x$V2, paste, collapse = ", ")
write.csv(x, file = "somefile.csv")
## now open up "somefile.csv" from your working directory

Upvotes: 1

Related Questions